From nobody Fri Dec 19 21:49:02 2025 Received: from SN4PR0501CU005.outbound.protection.outlook.com (mail-southcentralusazon11011071.outbound.protection.outlook.com [40.93.194.71]) (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 8AC982957CD; Sat, 8 Nov 2025 02:24:13 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=40.93.194.71 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1762568655; cv=fail; b=LmKuQtAYgbgoybyksVXH/08q3LTrgXUeOYqLRLdokhuMlxHMl5Ts19stLJlYJ189jBlhLxP6Kq8sgIwn0ZmgziOSQFgqOzdjcm22PY71KndTnxqgE9lg//zyG3ql5tzTMTtemJI9ahZTNmAHgCB5ssuPJY/Aklt9aipie1vNqxI= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1762568655; c=relaxed/simple; bh=DL3kJl47RLagLZb1lIAI+66xNgj7zmKgM369lPKqfyA=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=PgEfl0cuX6ldKKTvvX+weih9Yt3BK6s41iN5+aIowtqTNtUwE42XqaJEkEifvd+35vpcyqN0pDHCrnUNSG8lkh6ivXsskZN6xAvgKr5uEqYKVOx+tuaWs7fua5NGCPsHi19edXQPp3gTuJ6PRV5dgi5R3sPvDUWqUiejyypaIBc= 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=q3nFd3wl; arc=fail smtp.client-ip=40.93.194.71 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="q3nFd3wl" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=K/Zl21PyigOGwPFuoAi7Ut3WEzVKW4AJZXYtUYaDNJxQtx1r6imv/JPZTg97fc4j0nIycVdvTDhJP8e6XOwJ81oJWVdkQ63XcKg7jrY2no6jBYP7fZPwaR9B79SNaFCIj1oOWLg8dIkU4DVYFucOu+k5xxCneB2rE84S13mYHJNKkUUMWkrNJGfacXDm/liTq9+NEuVu3L4ViArXhZrXWFYjEpD8TnhcA20KWXYt+midSiJmKTco+jevG7FEkEul8wk7Sy54fo8cjpxnIKNk8pfaEgnr2XdTyA7vP0WLenCTs8ySV/6wKZn37m0bb3RFKv+up8rpHb061XjkaZNDCw== 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=aZ5uwyub0ifIcMx3+z4SZwPIsfyMINSer7ZBtFNzBWE=; b=ivJ59HBpfCrWOCQbSBmF5ubzmaYWWWUs8bjsg5ejDw43Qnd5/WJk9tCGm3/VlX03nlF4a3eVsfksN3g3yaWtBWUSzFXMfS92MzEpCBJIgdZ749A33JHudmAHQIgrGiLr1WI+kUy+sXkuJRn+/BNQD4pYq2K9z5GHNuE61bvDU0BR5BIXseLlUC4NGGCGmU/7+VJnV73QMNfMENYLqdJ8IKDoH+xm6yDnO1HHUxNGr4X6Nu6/ZtYIWx/Nyztvvq2yb9Xql23giKWYdaBbA/qXIoh/xuNxy4uzz1qcrA157qQx08ug35b98ApztXJcFICrU4PPrvqu5zzUXy8IgKqYhg== 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=aZ5uwyub0ifIcMx3+z4SZwPIsfyMINSer7ZBtFNzBWE=; b=q3nFd3wlDmgWH4fNlDULdvxOm/QLjPzQa5+cwEtKVjXTmtXWQj0EXb/uM8BM2Htd9A9vD7LlM17adQdY7CAvthLYy0m4dDfWBso3Pu03/a/AcRqVXGEz7ulyQ2WdS5nxqR4SH+2OExFDo5l6tC7AlLxms/3PSTmf6FKLmaB8brRcK3qjDEyQ9oorhC7lZ2Ws4NIyQ5DGdv6t+06HOU6ZXkphL+km2TsrG0j62OsiruI1Yq2OaXIwV/IzwjQpOAk3KiF26/XheRsyj4ggcQSH9z9n82Dd+mV18jSlmCE2L4R6Wg63Rwqkd0DNVgpBUg21T2j75kwg/m2WoZKWNi0mIA== 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 MN0PR12MB6149.namprd12.prod.outlook.com (2603:10b6:208:3c7::22) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9275.16; Sat, 8 Nov 2025 02:24:07 +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.9298.012; Sat, 8 Nov 2025 02:24:07 +0000 From: Alexandre Courbot Date: Sat, 08 Nov 2025 11:23:47 +0900 Subject: [PATCH v4 1/4] rust: add num module and Integer trait Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20251108-bounded_ints-v4-1-c9342ac7ebd1@nvidia.com> References: <20251108-bounded_ints-v4-0-c9342ac7ebd1@nvidia.com> In-Reply-To: <20251108-bounded_ints-v4-0-c9342ac7ebd1@nvidia.com> To: Alice Ryhl , Danilo Krummrich , Miguel Ojeda , Joel Fernandes , Yury Norov , Jesung Yang , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alexandre Courbot X-Mailer: b4 0.14.3 X-ClientProxiedBy: TYCP286CA0129.JPNP286.PROD.OUTLOOK.COM (2603:1096:400:2b6::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_|MN0PR12MB6149:EE_ X-MS-Office365-Filtering-Correlation-Id: 9e1d7fb5-1bbd-46ed-0167-08de1e6de4d0 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|10070799003|7416014|376014|1800799024|366016|921020; X-Microsoft-Antispam-Message-Info: =?utf-8?B?Mm9aTHY2TElvMmg2eE5WVEhoQm16cWdMUGUyR0d6VnJuUHNQZlgyMmVBWnR6?= =?utf-8?B?djZTajZhNGxoMXZrbXFkeGFRTHJuaEw2NkxvUjlyZW8wbTFUY3I2RkdTZmg3?= =?utf-8?B?bXRBUW81T1RBQThKSDlzREt1OU0vdkJBbkk0aWRsTXQrN3Vyc2xXTGNqYmFR?= =?utf-8?B?bFora2hrYlFiSjBlYm1RVFZJSkxmcG9tNHhWVUhNUzA3M3djTDRKeHRtSDh0?= =?utf-8?B?ZmZnb2h5eE9rTFFPK0Y2Q1U3US9WSUtMbEdqZUZ0UkxUQk5sNE1NcTlsMytw?=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CH2PR12MB3990.namprd12.prod.outlook.com;PTR:;CAT:NONE;SFS:(13230040)(10070799003)(7416014)(376014)(1800799024)(366016)(921020);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?QlFXeS9XMlpDcm5UQ1JNcDFmYnRQNWNFRmtrUlBucUpnZ1l5S2EzZWVPSFM3?= =?utf-8?B?S3ZkU1pGR05FeWhnZmNsRnZQMDFjL29CY0hWRTJFZmFkQnJHRkE5Q0V3REgw?= =?utf-8?B?Qzhnd2c5QXIxcVhXc01mUCtOVmdxc2QvYWY5ZklESEhsMWJodG91RE1MQ0xH?= =?utf-8?B?WmNPNFhsTW90MHdrSDdKNGF1TzJvTEp0MEpvTnNVRGFuU3VMdVg4dmtzaEpK?= =?utf-8?B?NXpodHpzaEFtK2xaeGZMZUhiQ2gvaTNwR1hVem43K0ZaV2hOakxPMTFINkxX?= =?utf-8?B?LzBHZy9vZVZWTWlGNW9RcjVuaWxqOHRzS3ArdnNWRkYvYVRmelVtSC8vL2J0?= =?utf-8?B?U2tHSDlGU0VYVzlBSkF4Y0N3eHdzWWYvSjNIOEYzRkgyVjU0M1E5eWRxREF1?= =?utf-8?B?WTkvRVpRdkFSVGh6NGQrN2ZlZWJtd3Y2clY4UDhNZFQzc3dJWlhRYkE1ai9j?= =?utf-8?B?YjYzM2FNYlM1ZWwyblFpdHF6RDhUaldRdDVTYUh5TkJBcjFROXF0eW5xVUNp?= =?utf-8?B?WmROb3VkVVRlRmFnMThwQ1hyQXR2SURiTGRYNDFpVTZ3bGNPMmhWTXpHblBn?= =?utf-8?B?d1lvUjNTMHg5TkpCMWdqNVA4bGx5YVIwQ1YveWVQc1Z0YXRKNzd1aFQxNWVF?= =?utf-8?B?RnVSa2RkdE1DUFRzeWVPTWpMbkZwUllyMy9rL1RZK2J2cVdQSHZEY2lYWjNi?= =?utf-8?B?dEZPemtBYmNYTEliM0kyVUhhY1Nw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VEF5NHVzRU5BNlF1ZndjYUNkM3F4SVFhTkxQVXFtRi9XZDFJc1ZxVmkr?= =?utf-8?B?eFNNeTVxTlkyM2RpQ1REM08xOERsOTlQVFRGcUhmY2R0MWZnSFF2cGlnU1RU?= =?utf-8?B?NU5hZEZRTTNETTdIdDducS9nMkpUem4xbW5yU1lyQTRQd3VLMmlnN1VYcHg5?= =?utf-8?B?VCszQlphd0k4Y1h1QkZCMjA1STBhSnl0ZmJ4amVVcy9XOGYxVHpzUTMxblRE?= =?utf-8?B?UjlTK0ZNdTJ2ZnRRcFFZWkpjOXRNcmcwNVVJVWpJTG9rNW1WVDMrTGlaUTcy?= =?utf-8?B?R0VlRjVnMHE0TVpZYmE4R0pqSDRZdXNqS0ZHeGxyWDlFdjZTSDBpeitkUWd1?= =?utf-8?B?OGZTaEt3amNEZWRZcmMwTmlmWk1ONHJTaE1Pczgva1dSNW1YalArK0k4ZWxC?= =?utf-8?B?ZHM3TFZtYktjOWhha1U3VXExOWtSRWFRYkdBY0FxTExraWtpSTd2RkROQi9r?= =?utf-8?B?QW1ybDhJQVRpZkVXTXF3SC8rTFZXdGV4bUw1TVZ6L1ZBY21iejhPVnNXV1dE?= =?utf-8?Q?j/lxBT4n78VUkYpE6448lOOryy58vjUDbqIb0M6Modm+?= X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 9e1d7fb5-1bbd-46ed-0167-08de1e6de4d0 X-MS-Exchange-CrossTenant-AuthSource: CH2PR12MB3990.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 08 Nov 2025 02:24:07.3817 (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: K05Z/q1lvRPQqDIJ/C3pJle4WErNt9Ya+9h9e8IHC0dF+paggTHO8vFuYyRyi6wY1xrTJoeML2RfYWupvPSKXg== X-MS-Exchange-Transport-CrossTenantHeadersStamped: MN0PR12MB6149 Introduce the `num` module, which will provide numerical extensions and utilities for the kernel. For now, introduce the `Integer` trait, which is implemented for all primitive integer types to provides their core properties to generic code. Signed-off-by: Alexandre Courbot Acked-by: Miguel Ojeda Reviewed-by: Alice Ryhl --- rust/kernel/lib.rs | 1 + rust/kernel/num.rs | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++= ++++ 2 files changed, 77 insertions(+) diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 3dd7bebe7888..235d0d8b1eff 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -109,6 +109,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..c8c91cb9e682 --- /dev/null +++ b/rust/kernel/num.rs @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Additional numerical features for the kernel. + +use core::ops; + +/// Designates unsigned primitive types. +pub enum Unsigned {} + +/// Designates signed primitive types. +pub enum Signed {} + +/// Describes core properties of integer types. +pub trait Integer: + Sized + + Copy + + Clone + + PartialEq + + Eq + + PartialOrd + + Ord + + ops::Add + + ops::AddAssign + + ops::Sub + + ops::SubAssign + + ops::Mul + + ops::MulAssign + + ops::Div + + ops::DivAssign + + ops::Rem + + ops::RemAssign + + ops::BitAnd + + ops::BitAndAssign + + ops::BitOr + + ops::BitOrAssign + + ops::BitXor + + ops::BitXorAssign + + ops::Shl + + ops::ShlAssign + + ops::Shr + + ops::ShrAssign + + ops::Not +{ + /// Whether this type is [`Signed`] or [`Unsigned`]. + type Signedness; + + /// Number of bits used for value representation. + const BITS: u32; +} + +macro_rules! impl_integer { + ($($type:ty: $signedness:ty), *) =3D> { + $( + impl Integer for $type { + type Signedness =3D $signedness; + + const BITS: u32 =3D <$type>::BITS; + } + )* + }; +} + +impl_integer!( + u8: Unsigned, + u16: Unsigned, + u32: Unsigned, + u64: Unsigned, + u128: Unsigned, + usize: Unsigned, + i8: Signed, + i16: Signed, + i32: Signed, + i64: Signed, + i128: Signed, + isize: Signed +); --=20 2.51.2 From nobody Fri Dec 19 21:49:02 2025 Received: from PH8PR06CU001.outbound.protection.outlook.com (mail-westus3azon11012057.outbound.protection.outlook.com [40.107.209.57]) (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 27C2F2C0F8E; Sat, 8 Nov 2025 02:24:19 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=40.107.209.57 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1762568661; cv=fail; b=CkqqcURa3NJRu52BR1GqceUFsZYmpJQ13Lg7VI98wg4vD6HyXL96DHy7PLhgBv4oqd9AZi4J6BrrvldE0fPTOnX73zwHYYUOzjJ1bj/+DdcWsx8bXuBIoXFdcPgDPtM2DDgotv16bCeYXabr9a7+FNxfy37CooT43AF7BLSjY3w= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1762568661; c=relaxed/simple; bh=OZpgh1Th1+75OMwd6aUJsA/RS0srPjAn6c/aSDRkL0M=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=NJarLVCXhOyVOFhd6NzAWORbyY7jCHICN5yclf2gbuVdStD52R/97Bs2+qAtdNGb5fQUYCRhgVC7a3bKYZ3tUS96azHwtDkCdMxK087zddQifujeMVr6vSU4tz1ibTkw2T/SXFYV07ksOuFW0M+gwsx+F45JOp2eKS3xg/0rZpI= 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=RUTDjNSz; arc=fail smtp.client-ip=40.107.209.57 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="RUTDjNSz" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=KhgzfKGw1hI2fkYjj4tdsQZdCk0Tc07kQ6TM7Vy7Fvpc4VqWdq6PW1SkrKqp3J0TG1wUrXuUjad3cfLEjfW35YbwtOh3VxhbokEethh+tkNC4h3+tho+nGZrEp6lpPyP1QHrM7eHh+qzY8wpD/V5KNSr9G22zTJJlBfQ/qSfQckjevNk9xSNW3m6JYvORMD+UZqELHO+KAqvuaKpXMed3ySPk5gs6vRVZd0stLGrD4a4Xi/86Q55PCxYWqssJIwegt47Br4L1hDoy1++SWHKn7qKpS8wVPw8T3CcDAE8LiJx0HzAeTkIAfcQaWYcUPh6J2ao8EiAkaQXo83iihP3Jw== 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=7hksASqTtco0talPGcxjE3jbDGqqHngKmcmEVj1e0J0=; b=hj8yogrq+qloBbwoIPjxEKaRvvdaWRw6joZQ4H0D2TDhnBoVuI2AEXHXyP8x55Y4gqVEDwWnX79u+jktpE5e/QfBa96O3Eoj38fw5nCDQ8pt22trFduWSJskuSxpfBJbkrUx5u9t0sfKHjVGTIcoXHYkS5I8rrtL3foJGsLndh+6WMZVj8S465w7ygAOgDTyfjX7451lVEiyJ9uyVeirRCAOdsS4JP7K+SDFvZKJRsu+I/3q8DfYMoniAU4KEtcdD/xzBVC2heAbZ/ZhNTw6IehyUB5MwszOzMmlbEYzp0QBBEg5ohIPfA+moXiBeLQ/bm3bHdFz6BlINiU5ZiPHjA== 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=7hksASqTtco0talPGcxjE3jbDGqqHngKmcmEVj1e0J0=; b=RUTDjNSzRByFqe5sK9kKZ1QsYAOER4q9HiaP97aBhA6jXl3kTxl1yUeW925Cxwb8fPDjUWhMG2+8S9HTAG2m5aYeBRVkeFNPNZTzP+NCBH0AlO0dLAKPLQX1vHZWUp4v4ITfIUa2kPPa6enImEdmySXyKy6LMgwjuGgqTe+gtdP5FIdZ1/7R1fYu6xm/QfRrM5TtA33/6M0xYKiZ+wJLAFd9KXmWRPl3gi9QAPVyII4cz2CBWTpNZFdsbVNkJdlw1HYOdWOikROdJWBMRecFI2UYK5ovD13J72fAHLwT3zr+BNto1W4xsUm9v7vc1PQo5rGsMJyoFD19u5tw/ulErw== 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 MN0PR12MB6149.namprd12.prod.outlook.com (2603:10b6:208:3c7::22) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9275.16; Sat, 8 Nov 2025 02:24:11 +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.9298.012; Sat, 8 Nov 2025 02:24:11 +0000 From: Alexandre Courbot Date: Sat, 08 Nov 2025 11:23:48 +0900 Subject: [PATCH v4 2/4] rust: num: add Bounded integer wrapping type Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20251108-bounded_ints-v4-2-c9342ac7ebd1@nvidia.com> References: <20251108-bounded_ints-v4-0-c9342ac7ebd1@nvidia.com> In-Reply-To: <20251108-bounded_ints-v4-0-c9342ac7ebd1@nvidia.com> To: Alice Ryhl , Danilo Krummrich , Miguel Ojeda , Joel Fernandes , Yury Norov , Jesung Yang , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alexandre Courbot X-Mailer: b4 0.14.3 X-ClientProxiedBy: TYCPR01CA0113.jpnprd01.prod.outlook.com (2603:1096:405:4::29) 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_|MN0PR12MB6149:EE_ X-MS-Office365-Filtering-Correlation-Id: 4eab5310-2ce9-47e2-0f42-08de1e6de6e4 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|10070799003|7416014|376014|1800799024|366016|921020; X-Microsoft-Antispam-Message-Info: =?utf-8?B?Rll6RTlOQWE1Vmx6aUN1c09OZisybno5REdtWDljWVNaNVZ0VWRTbkZIKzJ2?= =?utf-8?B?eThjMXU4TGVzam85dWlhdnc3M2d6eVpBL2pKTzBWYzVDVkNWTVVEbWJwZHBk?= =?utf-8?B?dUxCRjhpNDMxK2tMWU4zcDl3UG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dkZXY05RTnI2M1dhSmFvZVRrU2dzdkVwVE52MkE3RjhoNzJuS3UybUNGWEl5?= =?utf-8?Q?V/IGu/dzRvu30XPJXbJnzOhuJh0EaU=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)(10070799003)(7416014)(376014)(1800799024)(366016)(921020);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?UFFHRG5sTGtMTGxkTkdnQnJqV2VEbnBMbnFObkZsOFpvcjZRR2M0TzRuNHFl?= =?utf-8?B?eW05S1lhd1h2a0ZRTm1iSzFRUUw4OWxFMUo3TXpmK2cvSWozRWpNRUJNYk5E?= =?utf-8?B?TEN1eExsYXNUQXJ6QnVWSkJnY3h1ZUNpZmZFVXEzMUhMMUNNeXAzMm9mck5Y?= =?utf-8?B?SWQzTUtUMHlUc0dPVStmRHRxejk1azF3THQwV05JV3A0S1VZcy9mb054cTBj?= =?utf-8?B?NXpIZVNYTWJqRFgxN3AvREU3TlR3djdLdUxPNTJnT0hPM3htdS92Q1M3Y2NZ?= =?utf-8?B?dXRCdnRldTBhSmdWaGdHZjdJZS9nUWk2ejhKdkNQRDBoTXNRLy90bGg3RlJx?= =?utf-8?B?QTZqVkhNcjJJSXdHL3ZBbWZqUEVKL3pzeUtURDJ5bmQ2UVdUbTRuUXdFQWVi?= =?utf-8?B?SWlaM29sc3lSMTk1cmNPakJOdGdHTFBEUTllSmd5OEVDVmFsRWc4MnF2amtv?= =?utf-8?B?S1lzZ3dxbVRqdG8xWHBQR0dJa01Scm5pVThvNWFPd2ZxMjE3MElTb3Nlc3Fn?= =?utf-8?B?ajJqRW50OG81Tlo1KzMxYTlmbFJJQ3RLTi85WkhzTmJaN2NKK2xCQ1kyL09y?= =?utf-8?B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ckZR?= =?utf-8?B?OTZLWnIwaHJueWJjVGJkZFdIazhvRmF1ZjZMYWZkbkRvcXJmU2tIZTlvY0xD?= =?utf-8?B?b05SUWJoT01rK1dIOGhsazdRcC8raWJJWHl5QUVOZzI4TnhrSm1PWmtCV0V5?= =?utf-8?B?ZjdVTUViMzd4Rmh3S1paOEhBb3ZMdXlEZi95YUFtZDJNdktDNGVGS3pVSDc2?= =?utf-8?B?UE9tYmVRc1d1djdFRVgxZG85R29saEwwUnlickxVcFovS0JnNDVDUUdrOUdz?= =?utf-8?B?OHpyTFZ4WmpHM2RzcThPWWxDYzY0ZEdsc1htN2VNTlIyNC9FSFIxY2FtQk0x?= =?utf-8?B?S0lNeE1FZGQ1UldzZG1KOHFZaDg1UG1zWllhL3VkVVZqMkV3R3ZtRTA0T1hK?= =?utf-8?B?UElEZnRiVlJoWUl3c0x6TEZBZm00WEpXb3VZVGN3SXdueUN4LzhPS3pmZVcw?= =?utf-8?B?cnhzTlJyQU1pL3BWS0N3Tm82czNuV0oxSWh5YThISHJiS1l5cEh0TXRWSHVt?= =?utf-8?B?ZllORjVRdTA0eUJGU0xVek9LcnFtNTd6TW5BWkpQUFIvd2ZhWVdoL25NKzdW?= =?utf-8?B?TXIvNndVWmJ0cTFVV2VjNGNtQlN3MWJNUTlRTnVnci9adTlmVlVZMFg2eDVj?= =?utf-8?B?NkorV2VLQ3FLSEFmSVpRYzZoVjN4bmluUyswUnJ3S1QrekhKaTgrOTNIVUZH?= =?utf-8?Q?8aYf7kpIddp1u3nMaaWZkRoNvnwAi8TW0xJYGmXOvPxX?= X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 4eab5310-2ce9-47e2-0f42-08de1e6de6e4 X-MS-Exchange-CrossTenant-AuthSource: CH2PR12MB3990.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 08 Nov 2025 02:24:11.0119 (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: /90xa3oltQUerxlZ2dVomk8CubEzye3nkibO/O/byBAzU4vn6RmNYvTmn7JybvJFhjpushmxVQhtfN3RWGpBOg== X-MS-Exchange-Transport-CrossTenantHeadersStamped: MN0PR12MB6149 Add the `Bounded` integer wrapper type, which restricts the number of bits allowed to represent of value. This is useful to e.g. enforce guarantees when working with bitfields that have an arbitrary number of bits. Alongside this type, provide many `From` and `TryFrom` implementations are to reduce friction when using with regular integer types. Proxy implementations of common integer operations are also provided. Signed-off-by: Alexandre Courbot Acked-by: Miguel Ojeda Reviewed-by: Alice Ryhl --- rust/kernel/num.rs | 3 + rust/kernel/num/bounded.rs | 1054 ++++++++++++++++++++++++++++++++++++++++= ++++ 2 files changed, 1057 insertions(+) diff --git a/rust/kernel/num.rs b/rust/kernel/num.rs index c8c91cb9e682..8532b511384c 100644 --- a/rust/kernel/num.rs +++ b/rust/kernel/num.rs @@ -4,6 +4,9 @@ =20 use core::ops; =20 +pub mod bounded; +pub use bounded::*; + /// Designates unsigned primitive types. pub enum Unsigned {} =20 diff --git a/rust/kernel/num/bounded.rs b/rust/kernel/num/bounded.rs new file mode 100644 index 000000000000..8c304351a418 --- /dev/null +++ b/rust/kernel/num/bounded.rs @@ -0,0 +1,1054 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Implementation of [`Bounded`], a wrapper around integer types limiting= the number of bits +//! usable for value representation. + +use core::{ + cmp, + fmt, + ops::{ + self, + Deref, // + }, //, +}; + +use kernel::{ + num::Integer, + prelude::*, // +}; + +/// Evaluates to `true` if `$value` can be represented using at most `$n` = bits in a `$type`. +/// +/// `expr` must be of type `type`, or the result will be incorrect. +/// +/// Can be used in const context. +macro_rules! fits_within { + ($value:expr, $type:ty, $n:expr) =3D> {{ + let shift: u32 =3D <$type>::BITS - $n; + + // `value` fits within `$n` bits if shifting it left by the number= of unused bits, then + // right by the same number, doesn't change it. + // + // This method has the benefit of working for both unsigned and si= gned values. + ($value << shift) >> shift =3D=3D $value + }}; +} + +/// Returns `true` if `value` can be represented with at most `N` bits in = a `T`. +fn fits_within(value: T, num_bits: u32) -> bool { + fits_within!(value, T, num_bits) +} + +/// An integer value that requires only the `N` less significant bits of t= he wrapped type to be +/// encoded. +/// +/// This limits the number of usable bits in the wrapped integer type, and= thus the stored value to +/// a narrower range, which provides guarantees that can be useful when wo= rking with in e.g. +/// bitfields. +/// +/// # Invariants +/// +/// - `N` is greater than `0`. +/// - `N` is less than or equal to `T::BITS`. +/// - Stored values can be represented with at most `N` bits. +/// +/// # Examples +/// +/// The preferred way to create values is through constants and the [`Boun= ded::new`] family of +/// constructors, as they trigger a build error if the type invariants can= not be withheld. +/// +/// ``` +/// use kernel::num::Bounded; +/// +/// // An unsigned 8-bit integer, of which only the 4 LSBs are used. +/// // The value `15` is statically validated to fit that constraint at bu= ild time. +/// let v =3D Bounded::::new::<15>(); +/// assert_eq!(v.get(), 15); +/// +/// // Same using signed values. +/// let v =3D Bounded::::new::<-8>(); +/// assert_eq!(v.get(), -8); +/// +/// // This doesn't build: a `u8` is smaller than the requested 9 bits. +/// // let _ =3D Bounded::::new::<10>(); +/// +/// // This also doesn't build: the requested value doesn't fit within 4 s= igned bits. +/// // let _ =3D Bounded::::new::<8>(); +/// ``` +/// Values can also be validated at runtime with [`Bounded::try_new`]. +/// +/// ``` +/// use kernel::num::Bounded; +/// +/// // This succeeds because `15` can be represented with 4 unsigned bits. +/// assert!(Bounded::::try_new(15).is_some()); +/// +/// // This fails because `16` cannot be represented with 4 unsigned bits. +/// assert!(Bounded::::try_new(16).is_none()); +/// ``` +/// +/// Non-constant expressions can be validated at build-time thanks to comp= iler optimizations. This +/// should be used with caution, on simple expressions only. +/// +/// ``` +/// use kernel::num::Bounded; +/// # fn some_number() -> u32 { 0xffffffff } +/// +/// // Here the compiler can infer from the mask that the type invariants = are not violated, even +/// // though the value returned by `some_number` is not statically known. +/// let v =3D Bounded::::from_expr(some_number() & 0xf); +/// ``` +/// +/// Comparison and arithmetic operations are supported on [`Bounded`]s wit= h a compatible backing +/// type, regardless of their number of valid bits. +/// +/// ``` +/// use kernel::num::Bounded; +/// +/// let v1 =3D Bounded::::new::<4>(); +/// let v2 =3D Bounded::::new::<15>(); +/// +/// assert!(v1 !=3D v2); +/// assert!(v1 < v2); +/// assert_eq!(v1 + v2, 19); +/// assert_eq!(v2 % v1, 3); +/// ``` +/// +/// These operations are also supported between a [`Bounded`] and its back= ing type. +/// +/// ``` +/// use kernel::num::Bounded; +/// +/// let v =3D Bounded::::new::<15>(); +/// +/// assert!(v =3D=3D 15); +/// assert!(v > 12); +/// assert_eq!(v + 5, 20); +/// assert_eq!(v / 3, 5); +/// ``` +/// +/// A change of backing types is possible using [`Bounded::cast`], and the= number of valid bits can +/// be extended or reduced with [`Bounded::extend`] and [`Bounded::try_shr= ink`]. +/// +/// ``` +/// use kernel::num::Bounded; +/// +/// let v =3D Bounded::::new::<127>(); +/// +/// // Changes backing type from `u32` to `u16`. +/// let _: Bounded =3D v.cast(); +/// +/// // This does not build, as `u8` is smaller than 12 bits. +/// // let _: Bounded =3D v.cast(); +/// +/// // We can safely extend the number of bits... +/// let _ =3D v.extend::<15>(); +/// +/// // ... to the limits of the backing type. This doesn't build as a `u32= ` cannot contain 33 bits. +/// // let _ =3D v.extend::<33>(); +/// +/// // Reducing the number of bits is validated at runtime. This works bec= ause `127` can be +/// // represented with 8 bits. +/// assert!(v.try_shrink::<8>().is_some()); +/// +/// // ... but not with 6, so this fails. +/// assert!(v.try_shrink::<6>().is_none()); +/// ``` +/// +/// Infallible conversions from a primitive integer to a large-enough [`Bo= unded`] are supported. +/// +/// ``` +/// use kernel::num::Bounded; +/// +/// // This unsigned `Bounded` has 8 bits, so it can represent any `u8`. +/// let v =3D Bounded::::from(128u8); +/// assert_eq!(v.get(), 128); +/// +/// // This signed `Bounded` has 8 bits, so it can represent any `i8`. +/// let v =3D Bounded::::from(-128i8); +/// assert_eq!(v.get(), -128); +/// +/// // This doesn't build, as this 6-bit `Bounded` does not have enough ca= pacity to represent a +/// // `u8` (regardless of the passed value). +/// // let _ =3D Bounded::::from(10u8); +/// +/// // Booleans can be converted into single-bit `Bounded`s. +/// +/// let v =3D Bounded::::from(false); +/// assert_eq!(v.get(), 0); +/// +/// let v =3D Bounded::::from(true); +/// assert_eq!(v.get(), 1); +/// ``` +/// +/// Infallible conversions from a [`Bounded`] to a primitive integer are a= lso supported, and +/// dependent on the number of bits used for value representation, not on = the backing type. +/// +/// ``` +/// use kernel::num::Bounded; +/// +/// // Even though its backing type is `u32`, this `Bounded` only uses 6 b= its and thus can safely +/// // be converted to a `u8`. +/// let v =3D Bounded::::new::<63>(); +/// assert_eq!(u8::from(v), 63); +/// +/// // Same using signed values. +/// let v =3D Bounded::::new::<-128>(); +/// assert_eq!(i8::from(v), -128); +/// +/// // This however does not build, as 10 bits won't fit into a `u8` (rega= rdless of the actually +/// // contained value). +/// let _v =3D Bounded::::new::<10>(); +/// // assert_eq!(u8::from(_v), 10); +/// +/// // Single-bit `Bounded`s can be converted into a boolean. +/// let v =3D Bounded::::new::<1>(); +/// assert_eq!(bool::from(v), true); +/// +/// let v =3D Bounded::::new::<0>(); +/// assert_eq!(bool::from(v), false); +/// ``` +/// +/// Fallible conversions from any primitive integer to any [`Bounded`] are= also supported using the +/// [`TryIntoBounded`] trait. +/// +/// ``` +/// use kernel::num::{Bounded, TryIntoBounded}; +/// +/// // Succeeds because `128` fits into 8 bits. +/// let v: Option> =3D 128u32.try_into_bitint(); +/// assert_eq!(v.as_deref().copied(), Some(128)); +/// +/// // Fails because `128` doesn't fits into 6 bits. +/// let v: Option> =3D 128u32.try_into_bitint(); +/// assert_eq!(v, None); +/// ``` +#[repr(transparent)] +#[derive(Clone, Copy, Debug, Default, Hash)] +pub struct Bounded(T); + +/// Validating the value as a const expression cannot be done as a regular= method, as the +/// arithmetic operations we rely on to check the bounds are not const. Th= us, implement +/// [`Bounded::new`] using a macro. +macro_rules! impl_const_new { + ($($type:ty)*) =3D> { + $( + impl Bounded<$type, N> { + /// Creates a [`Bounded`] for the constant `VALUE`. + /// + /// Fails at build time if `VALUE` cannot be represented with = `N` bits. + /// + /// This method should be preferred to [`Self::from_expr`] whe= never possible. + /// + /// # Examples + /// ``` + /// use kernel::num::Bounded; + /// + #[doc =3D ::core::concat!( + "let v =3D Bounded::<", + ::core::stringify!($type), + ", 4>::new::<7>();")] + /// assert_eq!(v.get(), 7); + /// ``` + pub const fn new() -> Self { + // Statically assert that `VALUE` fits within the set numb= er of bits. + const { + assert!(fits_within!(VALUE, $type, N)); + } + + // INVARIANT: `fits_within` confirmed that `VALUE` can be = represented within + // `N` bits. + Self::__new(VALUE) + } + } + )* + }; +} + +impl_const_new!( + u8 u16 u32 u64 usize + i8 i16 i32 i64 isize +); + +impl Bounded +where + T: Integer, +{ + /// Private constructor enforcing the type invariants. + /// + /// All instances of [`Bounded`] must be created through this method a= s it enforces most of the + /// type invariants. + /// + /// The caller remains responsible for checking, either statically or = dynamically, that `value` + /// can be represented as a `T` using at most `N` bits. + const fn __new(value: T) -> Self { + // Enforce the type invariants. + const { + // `N` cannot be zero. + assert!(N !=3D 0); + // The backing type is at least as large as `N` bits. + assert!(N <=3D T::BITS); + } + + Self(value) + } + + /// Attempts to turn `value` into a `Bounded` using `N` bits. + /// + /// Returns [`None`] if `value` doesn't fit within `N` bits. + /// + /// # Examples + /// + /// ``` + /// use kernel::num::Bounded; + /// + /// let v =3D Bounded::::try_new(1); + /// assert_eq!(v.as_deref().copied(), Some(1)); + /// + /// let v =3D Bounded::::try_new(-2); + /// assert_eq!(v.as_deref().copied(), Some(-2)); + /// + /// // `0x1ff` doesn't fit into 8 unsigned bits. + /// let v =3D Bounded::::try_new(0x1ff); + /// assert_eq!(v, None); + /// + /// // The range of values representable with 4 bits is `[-8..=3D7]`. = The following tests these + /// // limits. + /// let v =3D Bounded::::try_new(-8); + /// assert_eq!(v.map(Bounded::get), Some(-8)); + /// let v =3D Bounded::::try_new(-9); + /// assert_eq!(v, None); + /// let v =3D Bounded::::try_new(7); + /// assert_eq!(v.map(Bounded::get), Some(7)); + /// let v =3D Bounded::::try_new(8); + /// assert_eq!(v, None); + /// ``` + pub fn try_new(value: T) -> Option { + fits_within(value, N).then(|| { + // INVARIANT: `fits_within` confirmed that `value` can be repr= esented within `N` bits. + Self::__new(value) + }) + } + + /// Checks that `expr` is valid for this type at compile-time and buil= d a new value. + /// + /// This relies on [`build_assert!`] and guaranteed optimization to pe= rform validation at + /// compile-time. If `expr` cannot be proved to be within the requeste= d bounds at compile-time, + /// use the fallible [`Self::try_new`] instead. + /// + /// Limit this to simple, easily provable expressions, and prefer one = of the [`Self::new`] + /// constructors whenever possible as they statically validate the val= ue instead of relying on + /// compiler optimizations. + /// + /// # Examples + /// + /// ``` + /// use kernel::num::Bounded; + /// # fn some_number() -> u32 { 0xffffffff } + /// + /// // Some undefined number. + /// let v: u32 =3D some_number(); + /// + /// // Triggers a build error as `v` cannot be asserted to fit within = 4 bits... + /// // let _ =3D Bounded::::from_expr(v); + /// + /// // ... but this works as the compiler can assert the range from th= e mask. + /// let _ =3D Bounded::::from_expr(v & 0xf); + /// + /// // These expressions are simple enough to be proven correct, but s= ince they are static the + /// // `new` constructor should be preferred. + /// assert_eq!(Bounded::::from_expr(1).get(), 1); + /// assert_eq!(Bounded::::from_expr(0xff).get(), 0xff); + /// ``` + pub fn from_expr(expr: T) -> Self { + crate::build_assert!( + fits_within(expr, N), + "Requested value larger than maximal representable value." + ); + + // INVARIANT: `fits_within` confirmed that `expr` can be represent= ed within `N` bits. + Self::__new(expr) + } + + /// Returns the wrapped value as the backing type. + /// + /// # Examples + /// + /// ``` + /// use kernel::num::Bounded; + /// + /// let v =3D Bounded::::new::<7>(); + /// assert_eq!(v.get(), 7u32); + /// ``` + pub fn get(self) -> T { + *self.deref() + } + + /// Increases the number of bits usable for `self`. + /// + /// This operation cannot fail. + /// + /// # Examples + /// + /// ``` + /// use kernel::num::Bounded; + /// + /// let v =3D Bounded::::new::<7>(); + /// let larger_v =3D v.extend::<12>(); + /// // The contained values are equal even though `larger_v` has a big= ger capacity. + /// assert_eq!(larger_v, v); + /// ``` + pub const fn extend(self) -> Bounded { + const { + assert!( + M >=3D N, + "Requested number of bits is less than the current represe= ntation." + ); + } + + // INVARIANT: the value did fit within `N` bits, so it will all th= e more fit within + // the larger `M` bits. + Bounded::__new(self.0) + } + + /// Attempts to shrink the number of bits usable for `self`. + /// + /// Returns [`None`] if the value of `self` cannot be represented with= in `M` bits. + /// + /// # Examples + /// + /// ``` + /// use kernel::num::Bounded; + /// + /// let v =3D Bounded::::new::<7>(); + /// + /// // `7` can be represented using 3 unsigned bits... + /// let smaller_v =3D v.try_shrink::<3>(); + /// assert_eq!(smaller_v.as_deref().copied(), Some(7)); + /// + /// // ... but doesn't fit within `2` bits. + /// assert_eq!(v.try_shrink::<2>(), None); + /// ``` + pub fn try_shrink(self) -> Option> { + Bounded::::try_new(self.get()) + } + + /// Casts `self` into a [`Bounded`] backed by a different storage type= , but using the same + /// number of valid bits. + /// + /// Both `T` and `U` must be of same signedness, and `U` must be at le= ast as large as + /// `N` bits, or a build error will occur. + /// + /// # Examples + /// + /// ``` + /// use kernel::num::Bounded; + /// + /// let v =3D Bounded::::new::<127>(); + /// + /// let u16_v: Bounded =3D v.cast(); + /// assert_eq!(u16_v.get(), 127); + /// + /// // This won't build: a `u8` is smaller than the required 12 bits. + /// // let _: Bounded =3D v.cast(); + /// ``` + pub fn cast(self) -> Bounded + where + U: TryFrom + Integer, + T: Integer, + U: Integer, + { + // SAFETY: the converted value is represented using `N` bits, `U` = can contain `N` bits, and + // `U` and `T` have the same sign, hence this conversion cannot fa= il. + let value =3D unsafe { U::try_from(self.get()).unwrap_unchecked() = }; + + // INVARIANT: although the backing type has changed, the value is = still represented within + // `N` bits, and with the same signedness. + Bounded::__new(value) + } +} + +impl Deref for Bounded +where + T: Integer, +{ + type Target =3D T; + + fn deref(&self) -> &Self::Target { + // Enforce the invariant to inform the compiler of the bounds of t= he value. + if !fits_within(self.0, N) { + // SAFETY: Per the `Bounded` invariants, `fits_within` can nev= er return `false` on the + // value of a valid instance + unsafe { core::hint::unreachable_unchecked() } + } + + &self.0 + } +} + +/// Trait similar to [`TryInto`] but for [`Bounded`], to avoid conflicting= implementations. +/// +/// # Examples +/// +/// ``` +/// use kernel::num::{Bounded, TryIntoBounded}; +/// +/// // Succeeds because `128` fits into 8 bits. +/// let v: Option> =3D 128u32.try_into_bitint(); +/// assert_eq!(v.as_deref().copied(), Some(128)); +/// +/// // Fails because `128` doesn't fits into 6 bits. +/// let v: Option> =3D 128u32.try_into_bitint(); +/// assert_eq!(v, None); +/// ``` +pub trait TryIntoBounded { + /// Attempts to convert `self` into a [`Bounded`] using `N` bits. + /// + /// Returns `None` if `self` does not fit into the target type. + fn try_into_bitint(self) -> Option>; +} + +/// Any integer value can be attempted to be converted into a [`Bounded`] = of any size. +impl TryIntoBounded for U +where + T: Integer, + U: TryInto, +{ + fn try_into_bitint(self) -> Option> { + self.try_into().ok().and_then(Bounded::try_new) + } +} + +// Comparisons between `Bounded`s. + +impl PartialEq> for Bounde= d +where + T: Integer, + U: Integer, + T: PartialEq, +{ + fn eq(&self, other: &Bounded) -> bool { + self.get() =3D=3D other.get() + } +} + +impl Eq for Bounded where T: Integer {} + +impl PartialOrd> for Bound= ed +where + T: Integer, + U: Integer, + T: PartialOrd, +{ + fn partial_cmp(&self, other: &Bounded) -> Option { + self.get().partial_cmp(&other.get()) + } +} + +impl Ord for Bounded +where + T: Integer, + T: Ord, +{ + fn cmp(&self, other: &Self) -> cmp::Ordering { + self.get().cmp(&other.get()) + } +} + +// Comparisons between a `Bounded` and its backing type. + +impl PartialEq for Bounded +where + T: Integer, + T: PartialEq, +{ + fn eq(&self, other: &T) -> bool { + self.get() =3D=3D *other + } +} + +impl PartialOrd for Bounded +where + T: Integer, + T: PartialOrd, +{ + fn partial_cmp(&self, other: &T) -> Option { + self.get().partial_cmp(other) + } +} + +// Implementations of `core::ops` for two `Bounded` with the same backing = type. + +impl ops::Add> for Bounded +where + T: Integer, + T: ops::Add, +{ + type Output =3D T; + + fn add(self, rhs: Bounded) -> Self::Output { + self.get() + rhs.get() + } +} + +impl ops::BitAnd> for Bounded= +where + T: Integer, + T: ops::BitAnd, +{ + type Output =3D T; + + fn bitand(self, rhs: Bounded) -> Self::Output { + self.get() & rhs.get() + } +} + +impl ops::BitOr> for Bounded<= T, N> +where + T: Integer, + T: ops::BitOr, +{ + type Output =3D T; + + fn bitor(self, rhs: Bounded) -> Self::Output { + self.get() | rhs.get() + } +} + +impl ops::BitXor> for Bounded= +where + T: Integer, + T: ops::BitXor, +{ + type Output =3D T; + + fn bitxor(self, rhs: Bounded) -> Self::Output { + self.get() ^ rhs.get() + } +} + +impl ops::Div> for Bounded +where + T: Integer, + T: ops::Div, +{ + type Output =3D T; + + fn div(self, rhs: Bounded) -> Self::Output { + self.get() / rhs.get() + } +} + +impl ops::Mul> for Bounded +where + T: Integer, + T: ops::Mul, +{ + type Output =3D T; + + fn mul(self, rhs: Bounded) -> Self::Output { + self.get() * rhs.get() + } +} + +impl ops::Rem> for Bounded +where + T: Integer, + T: ops::Rem, +{ + type Output =3D T; + + fn rem(self, rhs: Bounded) -> Self::Output { + self.get() % rhs.get() + } +} + +impl ops::Sub> for Bounded +where + T: Integer, + T: ops::Sub, +{ + type Output =3D T; + + fn sub(self, rhs: Bounded) -> Self::Output { + self.get() - rhs.get() + } +} + +// Implementations of `core::ops` between a `Bounded` and its backing type. + +impl ops::Add for Bounded +where + T: Integer, + T: ops::Add, +{ + type Output =3D T; + + fn add(self, rhs: T) -> Self::Output { + self.get() + rhs + } +} + +impl ops::BitAnd for Bounded +where + T: Integer, + T: ops::BitAnd, +{ + type Output =3D T; + + fn bitand(self, rhs: T) -> Self::Output { + self.get() & rhs + } +} + +impl ops::BitOr for Bounded +where + T: Integer, + T: ops::BitOr, +{ + type Output =3D T; + + fn bitor(self, rhs: T) -> Self::Output { + self.get() | rhs + } +} + +impl ops::BitXor for Bounded +where + T: Integer, + T: ops::BitXor, +{ + type Output =3D T; + + fn bitxor(self, rhs: T) -> Self::Output { + self.get() ^ rhs + } +} + +impl ops::Div for Bounded +where + T: Integer, + T: ops::Div, +{ + type Output =3D T; + + fn div(self, rhs: T) -> Self::Output { + self.get() / rhs + } +} + +impl ops::Mul for Bounded +where + T: Integer, + T: ops::Mul, +{ + type Output =3D T; + + fn mul(self, rhs: T) -> Self::Output { + self.get() * rhs + } +} + +impl ops::Neg for Bounded +where + T: Integer, + T: ops::Neg, +{ + type Output =3D T; + + fn neg(self) -> Self::Output { + -self.get() + } +} + +impl ops::Not for Bounded +where + T: Integer, + T: ops::Not, +{ + type Output =3D T; + + fn not(self) -> Self::Output { + !self.get() + } +} + +impl ops::Rem for Bounded +where + T: Integer, + T: ops::Rem, +{ + type Output =3D T; + + fn rem(self, rhs: T) -> Self::Output { + self.get() % rhs + } +} + +impl ops::Sub for Bounded +where + T: Integer, + T: ops::Sub, +{ + type Output =3D T; + + fn sub(self, rhs: T) -> Self::Output { + self.get() - rhs + } +} + +// Proxy implementations of `core::fmt`. + +impl fmt::Display for Bounded +where + T: Integer, + T: fmt::Display, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.get().fmt(f) + } +} + +impl fmt::Binary for Bounded +where + T: Integer, + T: fmt::Binary, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.get().fmt(f) + } +} + +impl fmt::LowerExp for Bounded +where + T: Integer, + T: fmt::LowerExp, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.get().fmt(f) + } +} + +impl fmt::LowerHex for Bounded +where + T: Integer, + T: fmt::LowerHex, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.get().fmt(f) + } +} + +impl fmt::Octal for Bounded +where + T: Integer, + T: fmt::Octal, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.get().fmt(f) + } +} + +impl fmt::UpperExp for Bounded +where + T: Integer, + T: fmt::UpperExp, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.get().fmt(f) + } +} + +impl fmt::UpperHex for Bounded +where + T: Integer, + T: fmt::UpperHex, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.get().fmt(f) + } +} + +/// Implements `$trait` for all [`Bounded`] types represented using `$num_= bits`. +/// +/// This is used to declare size properties as traits that we can constrai= n against in impl blocks. +macro_rules! impl_size_rule { + ($trait:ty, $($num_bits:literal)*) =3D> { + $( + impl $trait for Bounded where T: Integer {} + )* + }; +} + +/// Local trait expressing the fact that a given [`Bounded`] has at least = `N` bits used for value +/// representation. +trait AtLeastXBits {} + +/// Implementations for infallibly converting a primitive type into a [`Bo= unded`] that can contain +/// it. +/// +/// Put into their own module for readability, and to avoid cluttering the= rustdoc of the parent +/// module. +mod atleast_impls { + use super::*; + + // Number of bits at least as large as 64. + impl_size_rule!(AtLeastXBits<64>, 64); + + // Anything 64 bits or more is also larger than 32. + impl AtLeastXBits<32> for T where T: AtLeastXBits<64> {} + // Other numbers of bits at least as large as 32. + impl_size_rule!(AtLeastXBits<32>, + 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 32 bits or more is also larger than 16. + impl AtLeastXBits<16> for T where T: AtLeastXBits<32> {} + // Other numbers of bits at least as large as 16. + impl_size_rule!(AtLeastXBits<16>, + 16 17 18 19 20 21 22 23 + 24 25 26 27 28 29 30 31 + ); + + // Anything 16 bits or more is also larger than 8. + impl AtLeastXBits<8> for T where T: AtLeastXBits<16> {} + // Other numbers of bits at least as large as 8. + impl_size_rule!(AtLeastXBits<8>, 8 9 10 11 12 13 14 15); +} + +/// Generates `From` implementations from a primitive type into a [`Bounde= d`] with +/// enough bits to store any value of that type. +/// +/// Note: The only reason for having this macro is that if we pass `$type`= as a generic +/// parameter, we cannot use it in the const context of [`AtLeastXBits`]'s= generic parameter. This +/// can be fixed once the `generic_const_exprs` feature is usable, and thi= s macro replaced by a +/// regular `impl` block. +macro_rules! impl_from_primitive { + ($($type:ty)*) =3D> { + $( + #[doc =3D ::core::concat!( + "Conversion from a [`", + ::core::stringify!($type), + "`] into a [`Bounded`] of same signedness with enough bits to = store it.")] + impl From<$type> for Bounded + where + $type: Integer, + T: Integer::Signedness> + Fr= om<$type>, + Self: AtLeastXBits<{ <$type as Integer>::BITS as usize }>, + { + fn from(value: $type) -> Self { + // INVARIANT: The trait bound on `Self` guarantees that `N= ` bits is + // enough to hold any value of the source type. + Self::__new(T::from(value)) + } + } + )* + } +} + +impl_from_primitive!( + u8 u16 u32 u64 usize + i8 i16 i32 i64 isize +); + +/// Local trait expressing the fact that a given [`Bounded`] fits into a p= rimitive type of `N` bits, +/// provided they have the same signedness. +trait FitsInXBits {} + +/// Implementations for infallibly converting a [`Bounded`] into a primiti= ve type that can contain +/// it. +/// +/// Put into their own module for readability, and to avoid cluttering the= rustdoc of the parent +/// module. +mod fits_impls { + use super::*; + + // Number of bits that fit into a 8-bits primitive. + impl_size_rule!(FitsInXBits<8>, 1 2 3 4 5 6 7 8); + + // Anything that fits into 8 bits also fits into 16. + impl FitsInXBits<16> for T where T: FitsInXBits<8> {} + // Other number of bits that fit into a 16-bits primitive. + impl_size_rule!(FitsInXBits<16>, 9 10 11 12 13 14 15 16); + + // Anything that fits into 16 bits also fits into 32. + impl FitsInXBits<32> for T where T: FitsInXBits<16> {} + // Other number of bits that fit into a 32-bits primitive. + impl_size_rule!(FitsInXBits<32>, + 17 18 19 20 21 22 23 24 + 25 26 27 28 29 30 31 32 + ); + + // Anything that fits into 32 bits also fits into 64. + impl FitsInXBits<64> for T where T: FitsInXBits<32> {} + // Other number of bits that fit into a 64-bits primitive. + impl_size_rule!(FitsInXBits<64>, + 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 + ); +} + +/// Generates [`From`] implementations from a [`Bounded`] into a primitive= type that is +/// guaranteed to contain it. +/// +/// Note: The only reason for having this macro is that if we pass `$type`= as a generic +/// parameter, we cannot use it in the const context of `AtLeastXBits`'s g= eneric parameter. This +/// can be fixed once the `generic_const_exprs` feature is usable, and thi= s macro replaced by a +/// regular `impl` block. +macro_rules! impl_into_primitive { + ($($type:ty)*) =3D> { + $( + #[doc =3D ::core::concat!( + "Conversion from a [`Bounded`] with no more bits than a [`", + ::core::stringify!($type), + "`] and of same signedness into [`", + ::core::stringify!($type), + "`]")] + impl From> for $type + where + $type: Integer + TryFrom, + T: Integer::Signedness>, + Bounded: FitsInXBits<{ <$type as Integer>::BITS as usize= }>, + { + fn from(value: Bounded) -> $type { + // SAFETY: The trait bound on `Bounded` ensures that any v= alue it holds (which + // is constrained to `N` bits) can fit into the destinatio= n type, so this + // conversion cannot fail. + unsafe { <$type>::try_from(value.get()).unwrap_unchecked()= } + } + } + )* + } +} + +impl_into_primitive!( + u8 u16 u32 u64 usize + i8 i16 i32 i64 isize +); + +// Single-bit `Bounded`s can be converted from/to a boolean. + +impl From> for bool +where + T: Integer + Zeroable, +{ + fn from(value: Bounded) -> Self { + value.get() !=3D Zeroable::zeroed() + } +} + +impl From for Bounded +where + T: Integer + From, +{ + fn from(value: bool) -> Self { + // INVARIANT: a boolean can be represented using a single bit, and= thus fits within any + // integer type for any `N` > 0. + Self::__new(T::from(value)) + } +} --=20 2.51.2 From nobody Fri Dec 19 21:49:02 2025 Received: from PH8PR06CU001.outbound.protection.outlook.com (mail-westus3azon11012057.outbound.protection.outlook.com [40.107.209.57]) (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 656FD2C026B; Sat, 8 Nov 2025 02:24:17 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=40.107.209.57 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1762568659; cv=fail; b=Uk/wnP4f9KqNksHdkrlrqtJzh53xJbBb/mC9qxUg9pNv2TkE3WquxhKUCIH6qU24tapc+HFvVwwBHim4tGfidVxrqNFEmspjpt+O60cnqXRdgGnjAENSOEz6OUArbsqx4K79EMS0rAq8lVLpbKBZN3N1vo8ChkFD3XvU0TX2cps= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1762568659; c=relaxed/simple; bh=3zRpPJjaWfRyr3xEaIM6lAMSdycB1CRH0KLHMVYPZBM=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=bSE7C2AHkNarA8teXp6Rh+9TR0PibKbeXSMNlpvcuNFZPPoOII3Gam+7/pYM4ulF0bgTDFKP3zt402opM9OdRA1RwGZfkf1X003w8vrPot2KhgXbykSrgPxW5sIJkEZJkLaDQtxb0qFR92F+yaYSnoVoSEqcR5L3dVNlXc2y0xw= 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=M+dR5slu; arc=fail smtp.client-ip=40.107.209.57 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="M+dR5slu" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=wW2fsCDZZEca1XJ0oiz1wW68GBgjce0qzap65JPHNpYqns+HAAtcxHhkyM2GqaGCQhJO2wJeyP7IaiQEpowem8Zg1Hsc9g6saPuzxjSmmuttxb7YZNzAwaEJPtR/6FrQad5fY7NGtvwdpEg42igNppBto+/hVupX6SrB4i0nIwj+Ef/7Qqoe1L6IdHWYmEH2IKXZ9714pt88oVHpgrll6OcS95ByxM6RV48vRMXeJBREobtONn9j3D8/U5s9uev6ysl8FjkCuCfboF7HqR7o1GrtdDDgUuol0PNffN6fm/vQraOJuRY+SPxW2XYQCybU5oNn0YESdSuBtv0Ruq7CzA== 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=JZU52KZgmuHh4Bgh1GD4k8qt6qtLHOvspfRspftpLpQ=; b=jY8HSJ5viW2UidJko8rkQV19b6QVW9X0lequIfMpMZdKIksE7qBVNDpanuum+2Jg1bS/zuj+0JBKvj3zGjwV7NKe4555svwFJ7EmN0jY7iu2p8rwA9eVU/OBlXcXZ55nCvQCBng1ZcqOpqFzp0NoOXunIwSviQG1lgQVovE4nwJz1wOy+K2KLiymk4mmuM9/1MApLCblsJ8L+RB2qxNvPI9BGGuUIeTYKE6JRapBTuvrc9f3Z9kN4fDzTLKzD2U6im2GJiemLZ0MmbbTgwrZPDFYzKvLz8QFs90R9p2OOgxgmD+99S0SAi8TUM1D7mQPdaatWx2NC1ZwkS9OsFEkSQ== 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=JZU52KZgmuHh4Bgh1GD4k8qt6qtLHOvspfRspftpLpQ=; b=M+dR5slu6phhuoK9j8UTmWKTCVbI972RgrIf1S/2Ry2ZcR77E4i1ayRq9WRHzFv916QwSHfgYyR3nNZr+mlDwsbFJoMloeTO9j/XXuwmusPIEiE4k37qJ3U+5FPVS+wY58OIM9HYJIGTVhNJGqLpymqnLu9di5L82OzLOIY3kIY6lUdERLC0PbIqQARGgLIH2v0bE16yvtUgpleOTrU5lR57HBWQDK5YB8k2Rd9JALr92pdMiEnNziF4sBQ4hDGDPZkto86cE4t1n0mPEn1qa92kg9k/SEuq3HcRvLPZVPv/hljw4q7QEd9wme+YMqbC5h586kdycJmZwtMOo8B7kg== 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 MN0PR12MB6149.namprd12.prod.outlook.com (2603:10b6:208:3c7::22) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9275.16; Sat, 8 Nov 2025 02:24:14 +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.9298.012; Sat, 8 Nov 2025 02:24:14 +0000 From: Alexandre Courbot Date: Sat, 08 Nov 2025 11:23:49 +0900 Subject: [PATCH v4 3/4] MAINTAINERS: add entry for the Rust `num` module Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20251108-bounded_ints-v4-3-c9342ac7ebd1@nvidia.com> References: <20251108-bounded_ints-v4-0-c9342ac7ebd1@nvidia.com> In-Reply-To: <20251108-bounded_ints-v4-0-c9342ac7ebd1@nvidia.com> To: Alice Ryhl , Danilo Krummrich , Miguel Ojeda , Joel Fernandes , Yury Norov , Jesung Yang , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alexandre Courbot X-Mailer: b4 0.14.3 X-ClientProxiedBy: TYCP286CA0206.JPNP286.PROD.OUTLOOK.COM (2603:1096:400:385::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_|MN0PR12MB6149:EE_ X-MS-Office365-Filtering-Correlation-Id: 39564bf0-8679-422f-fd45-08de1e6de914 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|10070799003|7416014|376014|1800799024|366016|921020|7053199007; X-Microsoft-Antispam-Message-Info: =?utf-8?B?aDZyajhRUFFPQ1VrZ2pRVDNBeXhaZWJITktKb3pQNlZzUGdEcURQT0M1cCtS?= =?utf-8?B?NThYK3ArdzZjTXF4RTZaekcvZGxCanhuTlpSNW02YmRYeEx1UlhaRW5md0ly?= =?utf-8?B?azRhdnFBL0Y0QkQwQ2hud2oxaW5ERVdwNU9EeWIwVHhjVHA0UFZqV3E3VnpO?= =?utf-8?B?TDhiTllFTUdQejAyaDVSM1lLMFErWmJPaUp6Y0pvam5yTmdNbE5NOVJ3YTZU?= =?utf-8?B?QkdObC9JT0RDTFVjTzRIMWlJaDF2dFVWUDMrUHl3c3pwVVpkSmV1SGlyS2cx?= =?utf-8?B?NENXc0l6amtTd3E2Q2xiM0hiVjU5OEp2VWJZaDh6cC9INWhOU25EQVpVVzJ1?= =?utf-8?B?Y1RQL2RXc2J0cVBaRFJnOHhTRG9IVnFObzgzTVdGTi9odmFueUZ6UVY3RERm?= =?utf-8?B?eW9Xd0EzcGpPc3ZvUGN2MzltV2U5Sit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GcTBuOWVWRUVUTUxtNWRTZE53Mzl6QndDTEpzV3U4b0kv?= =?utf-8?B?OGRpdjYzY1FreUFZSDNUS2tnamtTZzEzWVZFdk80bmIxUDF0V1RrdzRKR1Iy?= =?utf-8?B?bURKOC9veVozN3hJalFZeG5UUy8yeFVGb3RreE1nOGFsM0k2ZDg2YTFleVI1?= =?utf-8?B?SmFKRUNHaG9Vb2V1aXcyVXM1bGpHazI0TGlrVWpDQTlLTUlIOHBTRkhQeE1i?= =?utf-8?B?NEVWMFY0enhnNXpJOUo3OTkxcU9TcDZGODA5RmR0aWFnM2JQWGxDQS8vaDh3?= =?utf-8?B?R2FYRXNsK3dEYTR2N3NZL3Voandia2VGa0RRaGJMSWFjdDJMbTd6SEwzNjhP?= =?utf-8?B?SUZSZUtMWWVSOHlUcHhsMmFuRm90bXU1dWNjb3g3ZGtWaWlBRTVOOUkzdlBE?= =?utf-8?B?SWFmUDU4ZkF6a29PNXJtOVArUzRGTVdpeUI1dGYrd1VJdU8weGZlQnErTDF1?= =?utf-8?B?TmFrRXdUOGhVMXd2b1VJb0tidDlJcE1zcUs0TkNuL2N2RFkwYzlYMUVlUjRi?= =?utf-8?B?ajRzWWFqd08xN3FpVGhXWnUrdlFoVVo1d2JNa0ZKR0VBQXhSSVlMTlIzdEZI?= =?utf-8?B?NlZ0RFNvOC96RGxPRUNvbjA3YXFCQjJ3RFdoV2RYYm1DdytHMUpkR1Y0d1pX?= =?utf-8?B?eC92SnIyRHUrY01Hc3FweUl1WExJZ3hDK1FCSEtTVk1JV25kRDhoNFM4K0hX?= =?utf-8?Q?/x21dS?= 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)(10070799003)(7416014)(376014)(1800799024)(366016)(921020)(7053199007);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 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uTXdUWUtTb3ZRNXVkZEIyaWNHTTNvUDJCOUhzSVRvRm9u?= =?utf-8?B?SkFhWFJEOTIzNDVMVWRGUTBCSURPaHRHODBVNmc2NTd0aUFpamUwU2wrQ1Ro?= =?utf-8?B?ZFBUanNRdFFicjJ2eGpxb2x0OUp5Q3pKcjBXV09URGN2UXA5THJsa3R4a2l2?= =?utf-8?B?SzMzdmc2aTUyQW9MOE5JcU5lTzlnSk1TYm9yaE1ZZ3FCRStqcjdOQ0JaRHdl?= =?utf-8?B?a2gxLzdtbWt2dkd2U1d2aXVjUUpkMjhxMlV6K2tPNG91dUJTekxSNHdpUjYv?= =?utf-8?B?dVJJMTczSU5HWUJJbnlXRGlSRkthcHpnY3QyZEcvbjFYaldpYzBuZE5hYUpW?= =?utf-8?B?UUY4Zi9Ua1Qwc2pwYU9xYUY1OWFVS3BTbVlrVVBjOTlFSGxoWUY5Y0JDRmtu?= =?utf-8?Q?YuankRS8iqwacfu/RLgM0WnejujNSK8QlHgvDC0kcuqU?= X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 39564bf0-8679-422f-fd45-08de1e6de914 X-MS-Exchange-CrossTenant-AuthSource: CH2PR12MB3990.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 08 Nov 2025 02:24:14.7789 (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: 0YDe1RaIviCfiVhHzjQzdyrhDdLayG+PyQMs3UhyrK73kphGowL1dNB5KrJ28upevpy59iLP4OAchnPxCpx+Yw== X-MS-Exchange-Transport-CrossTenantHeadersStamped: MN0PR12MB6149 This new module provides numerical features useful for the kernel, such as the `Integer` trait and the `Bounded` integer wrapper. Signed-off-by: Alexandre Courbot Acked-by: Miguel Ojeda Acked-by: Yury Norov (NVIDIA) Reviewed-by: Alice Ryhl --- MAINTAINERS | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index 952aed4619c2..b6294a2903c1 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -22521,6 +22521,14 @@ T: git https://github.com/Rust-for-Linux/linux.git= alloc-next F: rust/kernel/alloc.rs F: rust/kernel/alloc/ =20 +RUST [NUM] +M: Alexandre Courbot +R: Yury Norov +L: rust-for-linux@vger.kernel.org +S: Maintained +F: rust/kernel/num.rs +F: rust/kernel/num/ + RUST [PIN-INIT] M: Benno Lossin L: rust-for-linux@vger.kernel.org --=20 2.51.2 From nobody Fri Dec 19 21:49:02 2025 Received: from SN4PR0501CU005.outbound.protection.outlook.com (mail-southcentralusazon11011034.outbound.protection.outlook.com [40.93.194.34]) (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 2546F2BE7CD; Sat, 8 Nov 2025 02:24:25 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=40.93.194.34 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1762568669; cv=fail; b=OkAK8bJ9wlSBnOcsuNqrsdqie1RUBYKR8L8gFSD1AR0G+VFHFQ5D9hI4fGfy/8S/1EOZtIkAlvjxcnlIXAuJYGY5B7Okg91XwyEsRMbmfaY3Tp9Zucok4UjU6YW7WGCNAIAlOXTokXE6Rh0z1zRPJ4Q1lNhlCGBaA3V24TLuQ+A= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1762568669; c=relaxed/simple; bh=Be46L1a4in2dntzwbEEoYGQaw7hjSDxTjTLGAOL9eek=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=uiTwKaOG47svIRCEJ78Ji7dVKSHjX+VmYIqRsGt7UpQC5rcKyRNMTFSzTsi/QBoe6t2ctWagCuVtBeukumlZ+BAOlnjPqlpUvN7w5zA2sGxO6nHT2e8OyfKcRrXEF7LWuhFug2Rtm/D58qsUrBVUZgmf/L0SMXUuqXTguE/XXWI= 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=QBmSx6VU; arc=fail smtp.client-ip=40.93.194.34 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="QBmSx6VU" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=TFa9OHrMw26iq1Vf0ZN/CV2HRGn3MDj4FOb3YnzcnWKUr9vFQ55mbtlQC0YwRxYjUJKGumAGixLjW/9uLWpT/agO3jKtJV0tMmM6QfTEBXSM7eau0tKbsumfTeMiUvr31ifxfDHuZ+evnM/S4lqsRhxsAzDaCHziZVm5bZ7fZb/urV2DsAHPSViC4i8dT8pJzrKAWwIi78ZBHfPaF8Hn8CCneHr/8jDGAQnLEIEATQZLa+aAws/p6XxQ/H92xq/XoIB437noDzeO6NC+eEkD5cndM+cIJAcGoMj6xlf4ldMBreoLrmWkrqG2FPPLOP05OgGv69YDPgF0sGQDplixgA== 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=E+oGofHLK6cwft5AVPzLl/T3zAbIgZ2buxX45oDcgIY=; b=x1cXIK7ukUQ4pndVmWXoQYC0gbx2inxX0F4ZquuxxKmHHI2KKb3GuoTG5l6DBGbJFxSOdK6/6DkDSpi1lZwbzn2Q7EGV8LMgY0P4fXCwv0z+qBCQyhrxXqmJhONONCnPpDeOsTKceclDHXJNo3oALB16IeI/1WaDqJFM+pMmZkNVKQfpIj08uGPOYEloqb2AHABw6Bz0J+mtgGSw5Uztey9TrSPe4R6sxM765kZT2rNneEFpon4dBxNscpuWevq/19FHH51bpsLRiQSHwoTX/K6pWK/z6srA9zQDmkRhQe/rvNudCH+rIBpPXlmA398nhyf9RvNRiuV9WPSfBlFNuw== 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=E+oGofHLK6cwft5AVPzLl/T3zAbIgZ2buxX45oDcgIY=; b=QBmSx6VUb7XRpoqxpUrzidwC/6LJwLS7ASTIfzz1vOMWn2Y1nsJYGOAlQmvSeT6sV53rqJ+NiD2N+uBg57Ai14LG8Bjy0lY6tCySnNc8UPFTsNj/e88B+Gb13dUHNmmnRv+s3f23gFdVLQnTC25h9r043hts+tDmtugYryHV+RbUqFAE1EIVbyr62xZBQ0OfAC6Etd+ntNtzF40ZadEO2Dd19GqJavRs1I2I3xkY3fWofM7wdZs0rdD8+ZwTszO9hmngGR8xJYl1l/VamJnLRDn1CVood1IzYS4V/8QUQ2I5xP6tfS2ZjckC3APSS4oq5Y/8j9AY+QYS44WZNZsSfA== 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 MN0PR12MB6149.namprd12.prod.outlook.com (2603:10b6:208:3c7::22) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9275.16; Sat, 8 Nov 2025 02:24:18 +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.9298.012; Sat, 8 Nov 2025 02:24:18 +0000 From: Alexandre Courbot Date: Sat, 08 Nov 2025 11:23:50 +0900 Subject: [PATCH FOR REFERENCE v4 4/4] gpu: nova-core: use BitInt for bitfields Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20251108-bounded_ints-v4-4-c9342ac7ebd1@nvidia.com> References: <20251108-bounded_ints-v4-0-c9342ac7ebd1@nvidia.com> In-Reply-To: <20251108-bounded_ints-v4-0-c9342ac7ebd1@nvidia.com> To: Alice Ryhl , Danilo Krummrich , Miguel Ojeda , Joel Fernandes , Yury Norov , Jesung Yang , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alexandre Courbot X-Mailer: b4 0.14.3 X-ClientProxiedBy: TYCPR01CA0098.jpnprd01.prod.outlook.com (2603:1096:405:4::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_|MN0PR12MB6149:EE_ X-MS-Office365-Filtering-Correlation-Id: ef56f6e0-3ad4-426d-ea01-08de1e6deb77 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|10070799003|7416014|376014|1800799024|366016|921020; X-Microsoft-Antispam-Message-Info: =?utf-8?B?TFRUTHhZTE1xMmpKaVcyaldLU1N5R0g4VktKYngybW56VW9uUDlOS0EzeDBm?= =?utf-8?B?YjdoQXd3YU9EUytuVFViV3ZTWG51WnFuL055REw1anEvd1pCNXNXejdmNm5U?= =?utf-8?B?TWVKZ1p6MGE3a1BiNUl1SG9mZ0VHZWRvTm5ya0RUUHltYm42M3dHVERla2JM?= =?utf-8?B?TEtyQzhUT0o1VjVmS1RSNGxPSDhFTTFPVDh2OUlPOForcjhSSTVUbjN5czNn?= =?utf-8?B?dVRVaEhZT3ZyT2VzMGYzUms4Zm9ycDRKVEY1NWZWRUo0b3kzYTlaZ29RWHdY?= =?utf-8?B?MllNaFJ5TVEvQURLQ0xCSnNmUlprRFJjTFlJbi9oSW1JaG50SnM4Vjg1akZh?= =?utf-8?B?T0xLZjNmeW83ZGg0ZlU5QUhSN3pqZFRUazlCL3d0dzZXT0hNQmQvTDlZNDRC?= =?utf-8?B?WjFpL0Q0eFg5RDVkTCtEODlFeE50Q0ZGbXhGOUVPMCthUDQrQStIbXlRemUz?= =?utf-8?B?elZUcThMTVJZTW1TdEIvWkkzeTU1NFIrZnBHSmJOcHNMbkIxV0pGN2ZhSWt4?= =?utf-8?B?OExtSGtBclNjZWF6bUxWWUNWUkpZUVhxYlYzNXhCMVVYQXBPU1plUVd3TllF?= =?utf-8?B?RlFTZ1UwSXZSbTVSQi9uWUhob1JqMmllVy9rc0tuODlKYk5rRUNydkUzSEI0?= =?utf-8?B?b2lGa2U0MGg3ZWFNUmszcW4zVW1Uc0ZMRnNXU3hha05TTUVBTU9XWk9zS2Yw?= =?utf-8?B?S29NNSt0Q3I4bGxXUXRJM1UrblE3dnRIRjhtbTFTU05sVHNveDIyNkxmUHpN?= =?utf-8?B?UVRjUTR4Z2puaUpoK1d2VnMrN0ZBN3JIaEtlS01qRHlrRk9oMmhwWWNnRW5J?= =?utf-8?B?MEdkVEM3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f-8?B?aDIyU25QNEVuZDJMNWpoK0FpdVZub3JrT21UR3U0dzZLa25JL1U4ZlZmZ3FO?= =?utf-8?B?WDZUNFFXU0FMSGdSY21VdjROaG83TVl2QkFyOTRNeEcrWFJzdmg2emhpV2tn?= =?utf-8?B?Q1J1R0gwSm1BSms5T3EwWmczVTRPK0RJMXgybUUwcnhySWlIbEtHaDhXcVdH?= =?utf-8?B?UnBNM054OFZuS3hFQkdFamJHazJHR1RNRFVQZWsyVVVkZ2l3RCt4ZjRMQlpu?= =?utf-8?B?bVd6VGdrTjVqZ0RKVnFtcVEzTFQ2RTZ6Z3FtTnExTVB6MlNkK3NIMVIzN2g5?= =?utf-8?Q?w2OjeJ?= 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)(10070799003)(7416014)(376014)(1800799024)(366016)(921020);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?M3NQZ1dzN3hZU3RaemtjUVdxbVVQU1ljYUJSdENvdlhONVJWSnYwazZQNE1p?= =?utf-8?B?MmpsaEE5N0FSQWlMWlVLd0FoalJSWGV6V215TVlHSVorQVQ1TEVzeTN4di8x?= =?utf-8?B?Y2dtdERQQVRVaFZnQUtDRFg2cjd4SFlSakY4blU3cHlGUFBwWjVBNVY1a2gr?= =?utf-8?B?aWdtRVViNkVIRGVvcmN0UXJlYU8wRk5FUE0wa2NoNFRCdTVWNitzd1BpRENl?= =?utf-8?B?c0xQQ2xhSm9zQTZ0cTM0ZkVDcVk2eUdGRkxCMkM3V0tHeHJLVkhUUWhwcUVX?= =?utf-8?B?cnV2ajJPeWJMdzUxZFVWdTl5L3JnTEVFVC85Y1pSSVhhZm8wMzkxdHBBWTVx?= =?utf-8?B?VUtQREowTVdmajdYYjllU1B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?Q?t2p30lRDS4SYv2JYhpsSLa8cbI+xem6IvZWVs19SxrrY?= X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: ef56f6e0-3ad4-426d-ea01-08de1e6deb77 X-MS-Exchange-CrossTenant-AuthSource: CH2PR12MB3990.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 08 Nov 2025 02:24:18.6944 (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: ikZnHs4ViwNvFPPFJVWEmUzFkrqdlzgzVAZKsyIZUei3RPJmVj9pEkIgxjNVcyUd6H8JZEkNArr3Io2JXgIb6A== X-MS-Exchange-Transport-CrossTenantHeadersStamped: MN0PR12MB6149 Use BitInt with the bitfield!() and register!() macros 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 BitInt 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@gmail.= com/ [2] https://lore.kernel.org/rust-for-linux/20251003154748.1687160-1-joelagnelf@= nvidia.com/ Signed-off-by: Alexandre Courbot Acked-by: Miguel Ojeda Reviewed-by: Alice Ryhl --- drivers/gpu/nova-core/bitfield.rs | 366 ++++++++++++++++----------= ---- drivers/gpu/nova-core/falcon.rs | 145 ++++++------ drivers/gpu/nova-core/falcon/hal/ga102.rs | 5 +- drivers/gpu/nova-core/fb/hal/ga100.rs | 9 +- drivers/gpu/nova-core/gpu.rs | 9 +- drivers/gpu/nova-core/regs.rs | 139 ++++++------ 6 files changed, 365 insertions(+), 308 deletions(-) diff --git a/drivers/gpu/nova-core/bitfield.rs b/drivers/gpu/nova-core/bitf= ield.rs index 16e143658c51..be4d54feb38c 100644 --- a/drivers/gpu/nova-core/bitfield.rs +++ b/drivers/gpu/nova-core/bitfield.rs @@ -19,21 +19,21 @@ /// Auto =3D 2, /// } /// -/// impl TryFrom for Mode { -/// type Error =3D u8; -/// fn try_from(value: u8) -> Result { -/// match value { +/// impl TryFrom> for Mode { +/// type Error =3D u32; +/// fn try_from(value: Bounded) -> Result { +/// match *value { /// 0 =3D> Ok(Mode::Low), /// 1 =3D> Ok(Mode::High), /// 2 =3D> Ok(Mode::Auto), -/// _ =3D> Err(value), +/// value =3D> Err(value), /// } /// } /// } /// -/// impl From for u8 { -/// fn from(mode: Mode) -> u8 { -/// mode as u8 +/// impl From for Bounded { +/// fn from(mode: Mode) -> Bounded { +/// Bounded::from_expr(mode as u32) /// } /// } /// @@ -44,25 +44,29 @@ /// Active =3D 1, /// } /// -/// impl From for State { -/// fn from(value: bool) -> Self { -/// if value { State::Active } else { State::Inactive } +/// impl From> for State { +/// fn from(value: Bounded) -> Self { +/// if bool::from(value) { +/// State::Active +/// } else { +/// State::Inactive +/// } /// } /// } /// -/// impl From for bool { -/// fn from(state: State) -> bool { +/// impl From for Bounded { +/// fn from(state: State) -> Bounded { /// match state { -/// State::Inactive =3D> false, -/// State::Active =3D> true, +/// State::Inactive =3D> false.into(), +/// State::Active =3D> true.into(), /// } /// } /// } /// /// bitfield! { /// pub struct ControlReg(u32) { -/// 7:7 state as bool =3D> State; -/// 3:0 mode as u8 ?=3D> Mode; +/// 7:7 state =3D> State; +/// 3:0 mode ?=3D> Mode; /// } /// } /// ``` @@ -112,12 +116,9 @@ fn from(val: $name) -> $storage { 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. + // Dispatch fields depending on the syntax used. (@fields_dispatcher $vis:vis $name:ident $storage:ty { - $($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)? @@ -125,173 +126,208 @@ fn from(val: $name) -> $storage { )* } ) =3D> { - bitfield!(@field_accessors $vis $name $storage { - $( - $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 $vis:vis $name:ident $storage:ty { - $($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 $vis $name $storage, $hi:$lo $field = as $type - $(?=3D> $try_into_type)? - $(=3D> $into_type)? - $(, $comment)? - ; - ); - )* + $( + bitfield!(@private_field_accessors $name $storage : $hi:$lo $field= ); + bitfield!(@public_field_accessors $vis $name $storage : $hi:$lo $f= ield + $(?=3D> $try_into_type)? + $(=3D> $into_type)? + $(, $comment)? + ); + )* } + + bitfield!(@debug $name { $($field;)* }); + bitfield!(@default $name { $($field;)* }); + }; =20 - // 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 $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 $vis $name $storage, $hi:$lo $field - { |f| <$into_type>::from(f !=3D 0) } - bool $into_type =3D> $into_type $(, $comment)?; - ); - }; - - // Shortcut for fields defined as `bool` without the `=3D>` syntax. - ( - @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 bool = =3D> bool $(, $comment)?; - ); - }; - - // Catches the `?=3D>` syntax for non-boolean fields. - ( - @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 - { |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 $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 - { |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 $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)?; - ); - }; - - // Generates the accessor methods for a single field. - ( - @leaf_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $fi= eld:ident - { $process:expr } $prim_type:tt $to_type:ty =3D> $res_type:ty = $(, $comment:literal)?; + @private_field_accessors $name:ident $storage:ty : $hi:tt:$lo:tt $= field:ident ) =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 _MASK>]: u32 =3D ((((1 << $hi) - 1) << 1) + 1= ) - ((1 << $lo) - 1); const [<$field:upper _SHIFT>]: u32 =3D $lo; ); =20 + ::kernel::macros::paste!( + fn [<$field _internal>](self) -> + ::kernel::num::Bounded<$storage, { $hi + 1 - $lo }> { + const MASK: u32 =3D $name::[<$field:upper _MASK>]; + const SHIFT: u32 =3D $name::[<$field:upper _SHIFT>]; + + let field =3D ((self.0 & MASK) >> SHIFT); + + ::kernel::num::Bounded::<$storage, { $hi + 1 - $lo }>::from_ex= pr(field) + } + + fn []( + mut self, + value: ::kernel::num::Bounded<$storage, { $hi + 1 - $lo }>, + ) -> Self + { + const MASK: u32 =3D $name::[<$field:upper _MASK>]; + const SHIFT: u32 =3D $name::[<$field:upper _SHIFT>]; + + let value =3D (value.get() << SHIFT) & MASK; + self.0 =3D (self.0 & !MASK) | value; + + self + } + + fn []( + mut self, + value: T, + ) -> ::kernel::error::Result + where T: ::kernel::num::TryIntoBounded<$storage, { $hi + 1 - $= lo }>, + { + const MASK: u32 =3D $name::[<$field:upper _MASK>]; + const SHIFT: u32 =3D $name::[<$field:upper _SHIFT>]; + + let value =3D ( + value.try_into_bitint().ok_or(::kernel::error::code::EOVER= FLOW)?.get() << SHIFT + ) & MASK; + + self.0 =3D (self.0 & !MASK) | value; + + Ok(self) + } + ); + }; + + // Generates the public accessors for fields infallibly (`=3D>`) conve= rted to a type. + ( + @public_field_accessors $vis:vis $name:ident $storage:ty : $hi:tt:= $lo:tt $field:ident + =3D> $into_type:ty $(, $comment:literal)? + ) =3D> { + ::kernel::macros::paste!( + $( #[doc=3D"Returns the value of this field:"] #[doc=3D$comment] )? #[inline(always)] - $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>]; - ); - let field =3D ((self.0 & MASK) >> SHIFT); - - $process(field) + $vis fn $field(self) -> $into_type + { + self.[<$field _internal>]().into() } =20 - ::kernel::macros::paste!( $( #[doc=3D"Sets the value of this field:"] #[doc=3D$comment] )? #[inline(always)] - $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($prim_type::from(value)) << SHIF= T) & MASK; - self.0 =3D (self.0 & !MASK) | value; - - self + $vis fn [](self, value: $into_type) -> Self + { + self.[](value.into()) } + + /// Private method, for use in the [`Default`] implementation. + fn [<$field _default>]() -> $into_type { + Default::default() + } + + ); + }; + + // Generates the public accessors for fields fallibly (`?=3D>`) conver= ted to a type. + ( + @public_field_accessors $vis:vis $name:ident $storage:ty : $hi:tt:= $lo:tt $field:ident + ?=3D> $try_into_type:ty $(, $comment:literal)? + ) =3D> { + ::kernel::macros::paste!( + + $( + #[doc=3D"Returns the value of this field:"] + #[doc=3D$comment] + )? + #[inline(always)] + $vis fn $field(self) -> + Result< + $try_into_type, + <$try_into_type as ::core::convert::TryFrom< + ::kernel::num::Bounded<$storage, { $hi + 1 - $lo }> + >>::Error + > + { + self.[<$field _internal>]().try_into() + } + + $( + #[doc=3D"Sets the value of this field:"] + #[doc=3D$comment] + )? + #[inline(always)] + $vis fn [](self, value: $try_into_type) -> Self + { + self.[](value.into()) + } + + /// Private method, for use in the [`Default`] implementation. + fn [<$field _default>]() -> $try_into_type { + Default::default() + } + + ); + }; + + // Generates the public accessors for fields not converted to a type. + ( + @public_field_accessors $vis:vis $name:ident $storage:ty : $hi:tt:= $lo:tt $field:ident + $(, $comment:literal)? + ) =3D> { + ::kernel::macros::paste!( + + $( + #[doc=3D"Returns the value of this field:"] + #[doc=3D$comment] + )? + #[inline(always)] + $vis fn $field(self) -> + ::kernel::num::Bounded<$storage, { $hi + 1 - $lo }> + { + self.[<$field _internal>]() + } + + $( + #[doc=3D"Sets the value of this field:"] + #[doc=3D$comment] + )? + #[inline(always)] + $vis fn []( + self, + value: T, + ) -> Self + where T: Into<::kernel::num::Bounded<$storage, { $hi + 1 - $lo= }>>, + { + self.[](value.into()) + } + + $( + #[doc=3D"Attempts to set the value of this field:"] + #[doc=3D$comment] + )? + #[inline(always)] + $vis fn []( + self, + value: T, + ) -> ::kernel::error::Result + where T: ::kernel::num::TryIntoBounded<$storage, { $hi + 1 - $= lo }>, + { + Ok( + self.[]( + value.try_into_bitint().ok_or(::kernel::error::code::E= OVERFLOW)? + ) + ) + } + + /// Private method, for use in the [`Default`] implementation. + fn [<$field _default>]() -> ::kernel::num::Bounded<$storage, { $hi= + 1 - $lo }> { + Default::default() + } + ); }; =20 @@ -319,7 +355,7 @@ fn default() -> Self { =20 ::kernel::macros::paste!( $( - value.[](Default::default()); + value.[](Self::[<$field _default>]()); )* ); =20 diff --git a/drivers/gpu/nova-core/falcon.rs b/drivers/gpu/nova-core/falcon= .rs index fe5b3256d972..f74770703c0f 100644 --- a/drivers/gpu/nova-core/falcon.rs +++ b/drivers/gpu/nova-core/falcon.rs @@ -10,6 +10,10 @@ device, dma::DmaAddress, io::poll::read_poll_timeout, + num::{ + self, + Bounded, // + }, prelude::*, sync::aref::ARef, time::{ @@ -35,11 +39,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 Bounded + where + T: From + num::Integer, + { fn from(value: $enum_type) -> Self { - value as u8 + Bounded::from_expr(T::from(value as u8)) } } }; @@ -59,16 +66,20 @@ 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: num::Integer, + u8: From>, +{ type Error =3D Error; =20 - fn try_from(value: u8) -> Result { + fn try_from(value: Bounded) -> 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, @@ -94,24 +105,26 @@ 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: num::Integer, + u8: From>, +{ + fn from(value: Bounded) -> 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) + // SAFETY: `value` comes from a 2-bit `Bounded`, and we just c= hecked all possible + // values. + _ =3D> unsafe { core::hint::unreachable_unchecked() }, + } } } =20 @@ -138,16 +151,20 @@ 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: num::Integer, + u8: From>, +{ type Error =3D Error; =20 - fn try_from(value: u8) -> Result { + fn try_from(value: Bounded) -> 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, @@ -170,14 +187,18 @@ 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: num::Integer, + u8: From>, +{ type Error =3D Error; =20 - fn try_from(value: u8) -> Result { - match value { + fn try_from(value: Bounded) -> Result { + match u8::from(value) { 1 =3D> Ok(FalconModSelAlgo::Rsa3k), _ =3D> Err(EINVAL), } @@ -192,14 +213,18 @@ 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: num::Integer, + u8: From>, +{ type Error =3D Error; =20 - fn try_from(value: u8) -> Result { - match value { + fn try_from(value: Bounded) -> Result { + match u8::from(value) { 0x6 =3D> Ok(Self::Size256B), _ =3D> Err(EINVAL), } @@ -215,25 +240,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: num::Integer + Zeroable, +{ + fn from(value: Bounded) -> 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 { @@ -257,14 +277,18 @@ 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: num::Integer, + u8: From>, +{ type Error =3D Error; =20 - fn try_from(value: u8) -> Result { - let res =3D match value { + fn try_from(value: Bounded) -> Result { + let res =3D match u8::from(value) { 0 =3D> Self::LocalFb, 1 =3D> Self::CoherentSysmem, 2 =3D> Self::NoncoherentSysmem, @@ -284,26 +308,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: num::Integer + Zeroable, +{ + fn from(value: Bounded) -> 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 @@ -426,7 +445,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(()) @@ -495,20 +514,18 @@ fn dma_wr>( .set_base((dma_start >> 8) as u32) .write(bar, &E::ID); regs::NV_PFALCON_FALCON_DMATRFBASE1::default() - // CAST: `as u16` is used on purpose since the remaining bits = are guaranteed to fit - // within a `u16`. - .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(sec); =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 69a7a95cac16..72afbd9101cf 100644 --- a/drivers/gpu/nova-core/falcon/hal/ga102.rs +++ b/drivers/gpu/nova-core/falcon/hal/ga102.rs @@ -59,7 +59,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() @@ -68,7 +68,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 e0acc41aa7cd..acf46ad0dba1 100644 --- a/drivers/gpu/nova-core/fb/hal/ga100.rs +++ b/drivers/gpu/nova-core/fb/hal/ga100.rs @@ -1,6 +1,9 @@ // SPDX-License-Identifier: GPL-2.0 =20 -use kernel::prelude::*; +use kernel::{ + num::Bounded, + prelude::*, // +}; =20 use crate::{ driver::Bar0, @@ -20,9 +23,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() - // CAST: `as u32` is used on purpose since the remaining bits are = guaranteed to fit within - // a `u32`. - .set_adr_63_40((addr >> FLUSH_SYSMEM_ADDR_SHIFT_HI) as u32) + .set_adr_63_40(Bounded::from_expr(addr >> FLUSH_SYSMEM_ADDR_SHIFT_= HI).cast()) .write(bar); regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR::default() // CAST: `as u32` is used on purpose since we want to strip the up= per bits that have been diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs index 802e71e4f97d..faa1ab58b4fe 100644 --- a/drivers/gpu/nova-core/gpu.rs +++ b/drivers/gpu/nova-core/gpu.rs @@ -4,6 +4,7 @@ device, devres::Devres, fmt, + num::Bounded, pci, prelude::*, sync::Arc, // @@ -143,15 +144,15 @@ fn try_from(value: u8) -> Result { } =20 pub(crate) struct Revision { - major: u8, - minor: u8, + major: Bounded, + minor: Bounded, } =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 934003cab8a8..cb712c95b0bd 100644 --- a/drivers/gpu/nova-core/regs.rs +++ b/drivers/gpu/nova-core/regs.rs @@ -32,18 +32,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 @@ -64,7 +65,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 @@ -73,17 +74,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 { @@ -102,7 +103,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 { @@ -113,7 +114,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 { @@ -138,7 +139,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 @@ -148,7 +149,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 @@ -160,13 +161,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 @@ -180,8 +181,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 { @@ -200,40 +201,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 { @@ -244,101 +245,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 @@ -348,7 +349,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 @@ -356,6 +357,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; }); } --=20 2.51.2