From nobody Thu Apr 2 20:26:43 2026 Received: from DM1PR04CU001.outbound.protection.outlook.com (mail-centralusazon11010050.outbound.protection.outlook.com [52.101.61.50]) (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 1015D2727E2; Sat, 14 Mar 2026 01:06:34 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.61.50 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450396; cv=fail; b=pZ/tbhp7UQ+703kryV0PM04FxTLvmNmUJP+LtlkyRAwTNomxFVo1q/x1FRVMAaRfKIZbR2eNAl5+Y3I3lbKQB9S+Gi4JnCwnUzmht+OJxrP6bvS90C4N7MmM6nTfguO2Y5qZPMKSbFC6IMdpQO3rsYwJkx9B+7F/s6j8AEfEtX4= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450396; c=relaxed/simple; bh=0FP89CQyif/oPbzDEF0KNnDxci3xeSqE0b59wHIER0w=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=nokljz//RLHb2m9XVeAnfPfON63gYcNLdI145rcTSRJE8wp4DAemDp8oSKoyJUjbD3hEezfNuKyQ4OK0xdZUehTs4pitR8a/oq2qTiklbDdB2mlq+mThui6v/05A45Brio9kwxagNGswbWp1yq/+HFZtvGJrb2qHUx+NdpB+cc4= 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=rL6SeqwR; arc=fail smtp.client-ip=52.101.61.50 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="rL6SeqwR" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=y6HTmBDkVQ2F2LRlJyFX8TgDnTKlydYhyuJU2p7HAJxHkFXM00ThGK7h26k6mUwZg/nRLllZZPKaTKKIP0ZJnNNzl39N+hMo338pDSyOia+JjFoTlY7+jqmlee6byhvKzvYnWTyrZlrlcNFKFx8Gv1hcSbQngGMHBgICJWSlbm9dcBFxfeK1dhz+Xtm/FAyjHStpY4Z/nKk4mkQDHvd9Re0sd7lpgc03IW1UrXpHgVvaDTeB8lfxQGnybodNwbMvMlWLbviGdan5NbuX9TWeAFlBPiGcUAElXG8ZtRj8104Q5StTh417X6sM8jXjj6gv7KayHoOhqdKLIN1yOqolZw== 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=ae4UeDgfUfzoEEPMB/DfNXHA5UjZCs21uT8+xeI1MT8=; b=v8kSvBuq+/Sg+v5f8678zQyf95zhcaYMW+elbZO8EQ6i/ugcS4jt7qPjcc312ZDzMXrUVGzZwTJVF/mz6PgXVsPP64Hy58oX0vcJRZWYV9PrEyOSx2c9ANEoNZbv8rfBahj2wJU8qnwnv/Ohh5JDYOZ/O7bN76Yrwz8PrG7N8hQdvBGRC9EXzsv7SPBsreLCGNB7Z68KErNDk/hoDjWugvcJb2ZOxWWoU25gz77gVnYvwaxPUof60vMIkQYXWxN4G3Y2oYomyStNiAooKICCA6xZu0L2JdVs2adfCCh54taVuuXB+fxgRu3X87kwQzVV0QxHrLJUXteSER9x6gA/Gw== 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=ae4UeDgfUfzoEEPMB/DfNXHA5UjZCs21uT8+xeI1MT8=; b=rL6SeqwRuBLMWALFSZqNEDXTUnIxiRP4+3OFgXN2+mSTGLUKIkZswWepQnyvmOkwwHr7rJE1rde9sSFWcOfszyVJjfvWNT0IozD96/mbdf5UeWPAmQlllp622ouQ4Ike3W5j4tJ4pxk0N3xd8gGWx50OlWUneWgQPmDbqzG9LSB8bqLjY/k6tMvhA84T/ObUTiCV/ivvjPEgl1QdFvPTH7sCq/Be8kZ67DMZmKvdNrS5Y2NFUbZmOUnTPWbUDdAZZ3V+IVl686gkU6QbY3zGaD0Fow0kIMO1paxQHiM7rCh3X4lOLwxd6QY/B4T4LJ/SsIVUUnJTEmR74E93cV2MRw== 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 BY5PR12MB4033.namprd12.prod.outlook.com (2603:10b6:a03:213::22) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9723.6; Sat, 14 Mar 2026 01:06:31 +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.9723.000; Sat, 14 Mar 2026 01:06:31 +0000 From: Alexandre Courbot Date: Sat, 14 Mar 2026 10:06:11 +0900 Subject: [PATCH v9 01/10] rust: enable the `generic_arg_infer` feature Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260314-register-v9-1-86805b2f7e9d@nvidia.com> References: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> In-Reply-To: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> To: Danilo Krummrich , Alice Ryhl , Daniel Almeida , Miguel Ojeda , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Boqun Feng Cc: Yury Norov , John Hubbard , Alistair Popple , Joel Fernandes , Timur Tabi , Edwin Peer , Eliot Courtney , Dirk Behme , Steven Price , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alexandre Courbot X-Mailer: b4 0.14.3 X-ClientProxiedBy: TYCPR01CA0101.jpnprd01.prod.outlook.com (2603:1096:405:4::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_|BY5PR12MB4033:EE_ X-MS-Office365-Filtering-Correlation-Id: 95f50645-caa3-490b-119e-08de8165edc5 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|376014|7416014|10070799003|921020|22082099003|56012099003|18002099003; X-Microsoft-Antispam-Message-Info: SgvhwETMeOLxeYE8CRz5dbfCn4OvCaub7dd71aLjIa2SK88cUlBh6Q/sMgN+VfxKi9zz43xAQ3mC5UXnp9fwY5Wte2AoqqU5U+SwQyhnQ9hlrD6FNwguTbZXWykMhJQ2sWcnPYORednle2xAgHEQt+rBCT02tUBWpilC52XXbIF/MzdkDzRksXUpQC+R9d4QRRqr9i5m8IsKO2+GnaNcZOeuZVQInnCHBvtxcXmzjT7OBdxB5eqqXWR2R/IuHSfXC/CNvVUYEE8J/eHmrIvJ6av0xuJS9Js77q40e9Fyxe+xiu89mW4IK51kz+vu1ZrC5O3cnPWffAqBjZvI5S5V/Idg9/s5QHYqzzyszbHCMzTHhTIccBJdkgYFR9lbaTCmNRTFxyBPXV7k62xmOGl/3fCVfyVcfSIAQ6LaSMBJ3OwNF3KKtuSDNGcr2MKX2gAGLZC+UMl2vubwRyfv93lbYR7Q+pvrOJDR2bnU+CIQub9I0LwpCCTlVVFv89xvp/yUdJAcrrAFuUuzsmj+r0rNvbW2ZTi5IfXRsrgMEGY8w6jv1HO01Z8giQqt28QmoiCzp6hrLXamejJU0G7spqwbrPwONEgG0QfY5Ovk4sVsWLr5RQGG7kdhKdHR/U1CYZYsWYoKsJgDBYd6ut2EvSwuMk22dTixgRywAHvBGkNgcgC3rUSd2/J81XTqWntcpKtGxfR7s0c7xxDPySnPke62Yt3lCdrOxXKNGwczQ+2wbt8JjJfUHO1D0GzsdCPBFPfje+Kgfsa6R1AxV5SwFHP2ZpgIG7ZZ/CXJnhn7+fIWnTo= 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)(366016)(1800799024)(376014)(7416014)(10070799003)(921020)(22082099003)(56012099003)(18002099003);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 2 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?NnFVNDM0U2pEVHJtSVp4YmlYNm9KNUZnN1g1aW1ZdXZFRnJzZGJYRVZvU0hn?= =?utf-8?B?Q1NKTWVhNmZKOGlSUWhtWkw2MUdBZURnMnFvTllDOXNWRjhBRk1lbjcwUnBv?= =?utf-8?B?K0t1MWdMVUZyeDB0cUpLVDN0YTE5T0swUzg3MG1vUUtwTVVGNVhJYmdQYW9T?= =?utf-8?B?UExiU2FSQ21EL1FESk5pQ3lyZU9NdW13MmJJYmdBc2V2VUFJNitxakpwSlFr?= =?utf-8?B?eFhjUG5Ld1pNUkJYOGRlYnd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?= =?utf-8?B?TEZXRW5ycWtEWkNObW1LN005anViSDF6ZXZjbFhvMTkxc2dmcGtGUlNwcUdD?= =?utf-8?B?b2d0MmxDZVZpdyt5aEk0RDZqUGp5NWRucGs1eFVRTjhES3NPZFZ6eVRqWi9H?= =?utf-8?B?OCtqOFJsbkkxOEhJNENCSVJiS3hDWnBxanJXbFdHWXlJZ2c0Wm0rU3IwNlRt?= =?utf-8?B?TTVWMGJXYTNpd2NhVHY3THc3c0YvTWNBdHQrRFdFdG1aMnQvQTdnZ1BST3Ja?= =?utf-8?B?OGRicEpWUWl4M1VnTVRYaGlqZDNwVVJYWkczUjN6VE95cmhNcXpod1ZqcG9P?= =?utf-8?Q?mx7Wi018hvZTRRDqZHTbKXCPL9RuGg4Ya5hLoORNe6pXY?= X-MS-Exchange-AntiSpam-MessageData-1: FTXwh+2eEsIkOA== X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 95f50645-caa3-490b-119e-08de8165edc5 X-MS-Exchange-CrossTenant-AuthSource: CH2PR12MB3990.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 14 Mar 2026 01:06:31.5923 (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: vAANUt5f4RcVExMmD0ae8cAy8Zs1wp2h2Lyjspn0F61FRVZ+2IMF3f0oYyOqhGDaiN8zAa3XEeg3blnkmt8c9Q== X-MS-Exchange-Transport-CrossTenantHeadersStamped: BY5PR12MB4033 This feature is stable since 1.89, and used in subsequent patches. Reviewed-by: Gary Guo Tested-by: Dirk Behme Acked-by: Miguel Ojeda Signed-off-by: Alexandre Courbot --- rust/kernel/lib.rs | 3 +++ scripts/Makefile.build | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 3da92f18f4ee..cddeae8b6cb2 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -37,6 +37,9 @@ #![feature(const_ptr_write)] #![feature(const_refs_to_cell)] // +// Stable since Rust 1.89.0. +#![feature(generic_arg_infer)] +// // Expected to become stable. #![feature(arbitrary_self_types)] // diff --git a/scripts/Makefile.build b/scripts/Makefile.build index 32e209bc7985..923886735299 100644 --- a/scripts/Makefile.build +++ b/scripts/Makefile.build @@ -314,12 +314,13 @@ $(obj)/%.lst: $(obj)/%.c FORCE # - Stable since Rust 1.82.0: `feature(asm_const)`, # `feature(offset_of_nested)`, `feature(raw_ref_op)`. # - Stable since Rust 1.87.0: `feature(asm_goto)`. +# - Stable since Rust 1.89.0: `feature(generic_arg_infer)`. # - Expected to become stable: `feature(arbitrary_self_types)`. # - To be determined: `feature(used_with_arg)`. # # Please see https://github.com/Rust-for-Linux/linux/issues/2 for details = on # the unstable features in use. -rust_allowed_features :=3D asm_const,asm_goto,arbitrary_self_types,lint_re= asons,offset_of_nested,raw_ref_op,used_with_arg +rust_allowed_features :=3D asm_const,asm_goto,arbitrary_self_types,generic= _arg_infer,lint_reasons,offset_of_nested,raw_ref_op,used_with_arg =20 # `--out-dir` is required to avoid temporaries being created by `rustc` in= the # current working directory, which may be not accessible in the out-of-tree --=20 2.53.0 From nobody Thu Apr 2 20:26:43 2026 Received: from DM1PR04CU001.outbound.protection.outlook.com (mail-centralusazon11010018.outbound.protection.outlook.com [52.101.61.18]) (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 E9DE2272E7C; Sat, 14 Mar 2026 01:06:38 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.61.18 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450400; cv=fail; b=MwwmSV8Qiwi9WFAemRALxuEuSgTV9/sJD9yxVKWfEPUvNp9+SggkYl0God5FE/v/odU19+NbZBVdIpPpUW/zemnCIenC1mOC4hLxL3S0icn+1zTICy/i1U4I3s8wS46pgHIBTLuRMID8Kvpx+XlpNqU7jFXqY3o31zQF7BxGI68= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450400; c=relaxed/simple; bh=c0UGBMQRY8EiJxLPsEGtlbzdMgEjaS58LSVgjw60qmw=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=Gnduq6jVOPHPOc5lSo/eoTjSj3hyYc2Iz2HL/z68Etp6Ua6e/2TXDpyQdbMxEhf4itfhsgyKZd2aG8xRBQvA+zmsE+0bbnXNUt57jrKrjuopWoMwZ9QDn9OiNPwAL+YxuG6OhTSkgMWARcXvzNPFv8TXwnHf+gUvE9zfj7Strac= 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=OvYFQZij; arc=fail smtp.client-ip=52.101.61.18 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="OvYFQZij" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=SExZyjfIKxEhw0hAFMzYn4uqzhe9ekXM/kuPtJnWfy0DGcpW1B3bFdLeC6itb1Mzrq1bUxd8hnYmfgLd4FTzEFIJMVT47Jk8nA0di/suP66GAjF6bPG1eawT6yRVHwy2vzqHKXpwFZtPFxQb2CioB0EPl+rJLx6Mh9Lo5B+bj5m3vikud/deMQkYobmKhW9uQNi3zzsdBbmrJQu+58vCQw6ZQXKdf36IGXoGMptU1oV9IbsjvIrMjXnl0DSy/sQT/cjogvO32oF/FSSifX0FjAF/cmLimtIOlmnqIfXg7xuV2rvmmR7mwwaewJWwfBZZdixTKGXVqOSb9Q3UwGBzTw== 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=sSq1S2fZkmpSgFd7rALmgekh8GJ01tsbJVPBPo5ypy8=; b=Uy6zcF4OYO7aIiE9xY+EcbpO0pL8nXDB6sM6vQs2AyuMFKdSZDvbdnWVRWo2Ky/zuZ9hutInIhjUJXQYiJDXYEsc5E7Q5yykg90yaaWb2LTffqpt0ld/lykXrenPgxnI+YOZfQDE1p2tR9ZNznNrrrdIL8D5SElWwfi2tNKFX8E+oC6lY6fI20q3CuYBOFTwXUXtKMfKTRpVmct17RJrdksGW4ZKQaxJ3GW/IKyvL/rIW5dmHt57Cci/h5tOyn7xXkYWugSb5Azp5zX/nkoQLprjAaejZL5JZ+QJQo5HLFbN6qjnZ6coHNVp9GslU0sze2+EYKgavYnQNhElTDI0Rw== 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=sSq1S2fZkmpSgFd7rALmgekh8GJ01tsbJVPBPo5ypy8=; b=OvYFQZijpf9BK1nx3cIN/7rOxegN7QSNNyvNFj3FiC2GRoJo0KW1wrrnTz6189koRbOh9CN86vgoN8UMhL1x2axDzC8brNpwGy0v0W8n7NoYKPmTKcWWeEmN2ftGin6bANGul7N38mvADa7v99piVTXHlnEQeV/pGSfNZ76fmLTJvg4HoOcnRC8wITj3jBkHCzS+RGrozEy8QNI0jw8VtVO4PU+6ZLZus2e7eNC5Y11mrhbt4i9HhfPeIewAVYLqZJqYnRE5Fox8g7tHGcSJexJaEvseFWNIQ7m++CcU08Uk2H8oiiNJrciAMZm636pZyVabKE7mOEPOkfRe41c1Yg== 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 BY5PR12MB4033.namprd12.prod.outlook.com (2603:10b6:a03:213::22) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9723.6; Sat, 14 Mar 2026 01:06:35 +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.9723.000; Sat, 14 Mar 2026 01:06:35 +0000 From: Alexandre Courbot Date: Sat, 14 Mar 2026 10:06:12 +0900 Subject: [PATCH v9 02/10] rust: num: add `shr` and `shl` methods to `Bounded` Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260314-register-v9-2-86805b2f7e9d@nvidia.com> References: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> In-Reply-To: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> To: Danilo Krummrich , Alice Ryhl , Daniel Almeida , Miguel Ojeda , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Boqun Feng Cc: Yury Norov , John Hubbard , Alistair Popple , Joel Fernandes , Timur Tabi , Edwin Peer , Eliot Courtney , Dirk Behme , Steven Price , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alexandre Courbot , Yury Norov X-Mailer: b4 0.14.3 X-ClientProxiedBy: TYWP286CA0007.JPNP286.PROD.OUTLOOK.COM (2603:1096:400:178::15) 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_|BY5PR12MB4033:EE_ X-MS-Office365-Filtering-Correlation-Id: cbb06acf-6d44-4d5f-3a29-08de8165f029 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|376014|7416014|10070799003|921020|22082099003|56012099003|18002099003; X-Microsoft-Antispam-Message-Info: SeUmSgmH2XFRsqo2/8kbf4f518Js54+2jzkTkxvqJsI9jIDStYGaW4Ai2UboGPRjpiM8ZyCOqDdGsfSQ5TCUStZEHGcaCrd1Ubph8hz7GbdsWAqPWOAndn6H/cCWKVRXSQC+bUikEwiv0m9GD5uVJVJJmGXlog15iOsOXQUdrFm/TAvMm3WRNfcrpS84U1qTeA9Pem2OWwQKcSO4buxQJTkCShGvU4/mX2acVaw8la8dElNcch3QW3o1T0exeIbuKkyqEybpPptcQtlcqS68/Lq3id16Dp4yD/BHt0wSyYlHgGYPpl4eUZtXoXfn2kKf6wa6nYe/qekJKoSHxuZ8EHHqCf97kyg8mX+OgTfbtayJdspoyjuGsMleMEEbRXT0fK9FZ3jjDt5x0kW1PJPtBrmO5MKJpun+kvE2AOPKR49F39Y7y/SlNAveTEcEQEaJNfZPbf4BCRJLuoKVBTFh3kL+3fjpopeOEdeGqanCdNxJBVq+bW+0kFCytXIf1IeMCF8fjtAAiMW+2Aucml3xyNUV9BY/Oq9FaMnxT/rmkWB6jAeL+GFQPpDxbw+XlGnn9ZBJz8/L/wuHffsmKpiw8cJhxVZABBs9kAkeH606x4dDhDYRChzx1RgwFJBRVeVXthGxIuodUdYHv5NgsYYRjZO+LstT0uclaGXl2wpUnuXDZ6vVptg8v88ymwua6GXbk3M8dISGm74KXSZ2PCguZ7nteIPv5lqzOiofZu2jTKH1y+MhxuUivdCZEBAWKuzYG5L3qH3u/2NCbRD/amauAg== 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)(366016)(1800799024)(376014)(7416014)(10070799003)(921020)(22082099003)(56012099003)(18002099003);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 2 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?bEYvMVEycm1CT09obTgxa3M2bUU4dUxNWVlkUHNsbjZWemlMa1k2RjgzL09D?= =?utf-8?B?SGpDQXR4dHpnSXU2bDhYUVg4UFc5cDBLa242UTRpYXJqcE9BWXZ3d2hEWllX?= =?utf-8?B?c0JnRzE4ckc5ZVlWUitoMjBiU1pXYzJOR3Y1dy91ejk3VjZnVkVMUHhGQTZ4?= =?utf-8?B?OE5OUEVtOEVTN0lXckNmc3RVUHJtcm1OV2E0SVZlWFczV0NNTG9tVzlBMGNJ?= =?utf-8?B?cFJKblZvYktDaWZvNjBkZ2YvMXQ1R2xxcXVMMjdwazhMamNScXB5bDRaV2lG?= =?utf-8?B?VTdpQ0xFc1Bwbzd0SWEzTTlySUNBcXUrRG5paXhGWDAxV3gxTHJ5OGhrZzNj?= =?utf-8?B?blBzOEIwT0EvMGgxaWYrbDRyaEhDeTA1QS9FdHFkdXUyUHdERU9SU3JzbFQ3?= =?utf-8?B?U2xjd1I2aW5oMGFKczRZUXJMSWJDeWtCWDZ2K211WFdVODlPZUdDUVBWQUFS?= =?utf-8?B?dWdJMTdsVWlnS25sVm9GNDdmYndwRE9FZWExQ245MTJXOUlwT2p5a3lSTjRk?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Vdad3B6Y0w4bk1WaVczVE1QelFvcFJJT1ZOdkYyWGhrWEpidjE5eE42?= =?utf-8?Q?TY6pCUYQnFHsU8FxhQzuXamykBLZxq7M4mCYGfXFfofMO?= X-MS-Exchange-AntiSpam-MessageData-1: 3NJwnCc4TW8f8w== X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: cbb06acf-6d44-4d5f-3a29-08de8165f029 X-MS-Exchange-CrossTenant-AuthSource: CH2PR12MB3990.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 14 Mar 2026 01:06:35.6433 (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: s5rWJ1IL/6nH8Z8OGG/GX71sxCb9ZmfVQNvVD27Tj2/iFObemNKGgDKiWpojlccvl8fL2fxLiH7EjP/+tUxbBw== X-MS-Exchange-Transport-CrossTenantHeadersStamped: BY5PR12MB4033 Shifting a `Bounded` left or right changes the number of bits required to represent the value. Add methods that perform the shift and return a `Bounded` with the appropriately adjusted bit width. These methods are particularly useful for bitfield extraction. Suggested-by: Alice Ryhl Reviewed-by: Alice Ryhl Reviewed-by: Gary Guo Reviewed-by: Daniel Almeida Tested-by: Dirk Behme Acked-by: Miguel Ojeda Acked-by: Yury Norov Signed-off-by: Alexandre Courbot --- rust/kernel/num/bounded.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/rust/kernel/num/bounded.rs b/rust/kernel/num/bounded.rs index fa81acbdc8c2..2f5f13ecd3d6 100644 --- a/rust/kernel/num/bounded.rs +++ b/rust/kernel/num/bounded.rs @@ -473,6 +473,48 @@ pub fn cast(self) -> Bounded // `N` bits, and with the same signedness. unsafe { Bounded::__new(value) } } + + /// Right-shifts `self` by `SHIFT` and returns the result as a `Bounde= d<_, RES>`, where `RES >=3D + /// N - SHIFT`. + /// + /// # Examples + /// + /// ``` + /// use kernel::num::Bounded; + /// + /// let v =3D Bounded::::new::<0xff00>(); + /// let v_shifted: Bounded:: =3D v.shr::<8, _>(); + /// + /// assert_eq!(v_shifted.get(), 0xff); + /// ``` + pub fn shr(self) -> Bounded { + const { assert!(RES + SHIFT >=3D N) } + + // SAFETY: We shift the value right by `SHIFT`, reducing the numbe= r of bits needed to + // represent the shifted value by as much, and just asserted that = `RES >=3D N - SHIFT`. + unsafe { Bounded::__new(self.0 >> SHIFT) } + } + + /// Left-shifts `self` by `SHIFT` and returns the result as a `Bounded= <_, RES>`, where `RES >=3D + /// N + SHIFT`. + /// + /// # Examples + /// + /// ``` + /// use kernel::num::Bounded; + /// + /// let v =3D Bounded::::new::<0xff>(); + /// let v_shifted: Bounded:: =3D v.shl::<8, _>(); + /// + /// assert_eq!(v_shifted.get(), 0xff00); + /// ``` + pub fn shl(self) -> Bounded { + const { assert!(RES >=3D N + SHIFT) } + + // SAFETY: We shift the value left by `SHIFT`, augmenting the numb= er of bits needed to + // represent the shifted value by as much, and just asserted that = `RES >=3D N + SHIFT`. + unsafe { Bounded::__new(self.0 << SHIFT) } + } } =20 impl Deref for Bounded --=20 2.53.0 From nobody Thu Apr 2 20:26:43 2026 Received: from PH8PR06CU001.outbound.protection.outlook.com (mail-westus3azon11012044.outbound.protection.outlook.com [40.107.209.44]) (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 BCAA82550D5; Sat, 14 Mar 2026 01:06:42 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=40.107.209.44 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450404; cv=fail; b=DQQgFfrktFdVTP4P02oj+InxxgFYYAEgs44KWenVn5Y7WZn4+aTUGYOsZllTIdViVoIsodcR6kyASwB1OxmEJ+2qZDNOfWbzAEufc1TdUKnmQmY4AvllDaZEVBnC9Vli3cW/RsQkk3zYeHOckaVoJD3XQkhRgaY8eceILZpfN8g= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450404; c=relaxed/simple; bh=Uam97JT0Ehkz6x3YfVS2uBfORH+d7sDDZqDf3SfLJzs=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=bkQiGWUg2VY6E6ZEI2HFyBsUhmhEYGhiM0z4l27URaM++zwIk8U9Tq/OyOG2stO5TdhiO2Jo5GaLawRVVmTHJooG5ghwlhdxNrfJXZ3EZSn9wM9eSX2PuUXzDVtrA3uncBN1zW2ix6xheYtfi/iQKIDJQOWgf7tFVPjB1SNQa0U= 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=tEvo7zxs; arc=fail smtp.client-ip=40.107.209.44 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="tEvo7zxs" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=R71rF5qex2bd7+dEjWme6UGubxzzdZGtbEKW7UBAI7J8omYSQo5dmhRS4OWNuDstvSme+mOu1/EpYapcjtt7EawoFmzoHF0reYJ7tO1m/48w4ecU7yahjzJqOzVf53I9rtqTd5FL50WMuOSqRVcBdWPqnIvYo1oXnFpEViPSgVSG3oZQZ07H662lJnbRdVh19J2kSMoC7DYVdzT6LlJGgY+2X0L99ZH8QghRe51fxM44g/RJNPD9Lg7LkncAHdtdMGzuOtJHGF74OQEPLKDyJMF0nKGh1iHPXhn0jTCfJlIx12nxNFwEkC3ZX9izOp6gJxsuHJL8JtkwVzFK6yUZzw== 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=Mi+lYxjp8u893uwLtsJsUKUul8Qe5SJoOXAXtyxndjo=; b=hDg36rZS10M+sSPltvZfDw9BBnb9WK562xabk11KtGRy/7xgol+hxMvZE0IMREla2UDMBAJOlQXCrHBcgGLlJ+GNYMKjI8B4YJCin0vYPSs+tBOd7Ao9S6XzPFMDTqSxxD8IXKmQRGI6PP/fKqvEEVMDeHWPasCaGiic822cREAaYPyda6zzCGCBn0T2XfukwQGbvSYjheknB8ryIxbiqeEmv+jDo89Ol1AoLJRc1MLrMj5SK4NCMCo7Ienf14Wlrn3KZuMu90VZGiNGWJ73PuelRbP4wt/9HgGC09lkFlr8SRzhOOa1lh6hdD1CXvssi5oWKRnoTaObccYAl0nA2Q== 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=Mi+lYxjp8u893uwLtsJsUKUul8Qe5SJoOXAXtyxndjo=; b=tEvo7zxsUw+XkR+flKdqKaRaMT1KgGxN4fjspvi5hvDt5itFFuNVpml8XxteCY+9mbph1SIZ4g4a/TBCjhsaKk3/zTiW3VhwBPy7pPxhTP9VscakcFc/GJ8ARC5FkhslDzwX4UTm/kq8SpNYVHUgL0ChX1xJEQ0VpQfIilcpZ5i5HaYdVeGk5lXk5TWoY9652lmH0yhjxJ1na7vgF9Nigax/RAgq9/Hpm0ZlV1pE9L7xuDjjR6SxXwTwfGDNO7fk0oyYlrOzdIlA3nLjaO+9lMkqcw4mknh71uALly/PKKSzSRpomTisXvbU1jzRrYKccy6XqwZeFq8Cg3v1Om87vw== 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 BY5PR12MB4033.namprd12.prod.outlook.com (2603:10b6:a03:213::22) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9723.6; Sat, 14 Mar 2026 01:06:39 +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.9723.000; Sat, 14 Mar 2026 01:06:39 +0000 From: Alexandre Courbot Date: Sat, 14 Mar 2026 10:06:13 +0900 Subject: [PATCH v9 03/10] rust: num: add `into_bool` method to `Bounded` Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260314-register-v9-3-86805b2f7e9d@nvidia.com> References: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> In-Reply-To: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> To: Danilo Krummrich , Alice Ryhl , Daniel Almeida , Miguel Ojeda , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Boqun Feng Cc: Yury Norov , John Hubbard , Alistair Popple , Joel Fernandes , Timur Tabi , Edwin Peer , Eliot Courtney , Dirk Behme , Steven Price , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alexandre Courbot X-Mailer: b4 0.14.3 X-ClientProxiedBy: TYXPR01CA0065.jpnprd01.prod.outlook.com (2603:1096:403:a::35) 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_|BY5PR12MB4033:EE_ X-MS-Office365-Filtering-Correlation-Id: 1e454ff1-a197-4e55-1224-08de8165f282 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|376014|7416014|10070799003|921020|7053199007|22082099003|56012099003|18002099003; X-Microsoft-Antispam-Message-Info: 7d6C/3oaaGoyAMrvPYbClfzQ+oIcn7zifZNvFAZFhgfy0OsagMrQz29XyZJSSD1rBgum+UylJyNPyR88L5XZJK9Bd1WorzoDZtjqL+JYomZ2vGvNVjeNGw6vNGKzbCdpfvRJGdFuCGUgJY+raYRCLjgFX7wawjMcbs6BFM8gh5XRqkPZ1RXcIPYyQ6gVrbMCzG3kyTqwUgRdnwJtW8wKymTI470ETE8cYDoN+u4I9AFhoEm2BGQ1isFAwVAjGbHDoUeDO5RXopnL7drPHxRPV0hbrD1suA98hO/TZI2yz/39IAF2q3cNivSgRE3ZEADYiS/FQYuLQ0cCQ/oLOAO0BMYns9PTlwHun8lp6WR255JTBwXVvnaHsuP5Licygeyf2fC7ciduO8vFBpW8hgUYgkwXi6PGjVaxIbIlCcjZUgrWY/ZVigayujHt7FfNNvAciu91XrATkdVj1O5MwWYjFobiChcvfCeDw/Qf6KbStgOcWt2MKEo+armrqILDinqXp0OQ5jnzs+mZldShGi6aMUXGf1r00/X0dQs6Uln8v2Rcj6ya9R8yRUXE0K/QNWfEOzWGeh6xYMgS3Wgt9NhtHP5Pl8XW/GUnqVjwvhoS0Uqj6vUc/YJOTcBHiYyyRCjOfOAMtTfxTpFm1ZOhb3xs1HZPYabcG79YX77tjXPFYYHEtt6iov8v4IB5clbugstC21OysoW9OEatlvWKloMhAvn7vE1XljALXYZo9xcFjKVbrlIskoWIyfsYhf3s7bfgLsOZNDdLEL3Kr2o4WGRafw== 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)(366016)(1800799024)(376014)(7416014)(10070799003)(921020)(7053199007)(22082099003)(56012099003)(18002099003);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 2 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?Q3Jndlp4SEY2UkM4elhhVXBNczU5cDIvSnN0WkNYM011Q2JkN2ExOXFXQ1pD?= =?utf-8?B?bktwWGVKV3hJVDJxVE8rV2I1UmZBM3NtVnkwaVZpSENSdWVNR3l4cytlMjlT?= =?utf-8?B?QWdwQURpZkQ4TEpRbWRleGF2R3l5M0FtU2VXWlJqTEZvaDJMR1F1SCt1YmlW?= =?utf-8?B?WkExYUhyT2U1bzBoZDk0UGFEWW8rMHFmVUV6MnNSTHVuaVgvbW5XYVZIcFd4?= =?utf-8?B?U1hvUHE2cWRtKzNrZlMzYmkycGhzZVhFYzlXckU4aTZSejE3ZXd6cFcwZmJh?= =?utf-8?B?NHZIdHZnMXk3MDVyZU55eVp4dGxzY0VzdDBsbEJwd2RZL1JoTE5mei92UkFw?= =?utf-8?B?VEF4N2Y2N1JLUzJjRUpYMm8xT2ZKMnpvRW9BQll2bjU2clBaV2pnMTlzeURD?= =?utf-8?B?TkpBc1BVV0xCdXlKSXd3R29lSGxKR21DZ2hFaU92am5jS2JHSXhEdThJSEo2?= =?utf-8?B?QlRoYW83ckFiWUI0NFBQcDhQUENETCt0blJuek9kV3hwS1pCTUtDVGpKYy90?= =?utf-8?B?azUvRkgwdVE4eHE0aDJEOWdVZ3VyVDBXc0FDVXNzQXpELzNnSkIx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kzhhjBTr83pyrgwulAUiHshU21h9wbjofpc1DelO1Y?= X-MS-Exchange-AntiSpam-MessageData-1: og3o40KzCTSpUg== X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 1e454ff1-a197-4e55-1224-08de8165f282 X-MS-Exchange-CrossTenant-AuthSource: CH2PR12MB3990.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 14 Mar 2026 01:06:39.5061 (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: 6bXF767dsDJ54qe9jnp0nptaWuV+jv01IxYAcEnZt83nkO3llOnjDPFF7zpWZ0dVhppaFJyIOH7a6gSS1JahGQ== X-MS-Exchange-Transport-CrossTenantHeadersStamped: BY5PR12MB4033 Single-bit numbers are typically treated as booleans. There is an `Into` implementation for those, but invoking it from contexts that lack type expectations is not always convenient. Add an `into_bool` method as a simpler shortcut. Reviewed-by: Alice Ryhl Reviewed-by: Gary Guo Reviewed-by: Daniel Almeida Reviewed-by: Yury Norov Tested-by: Dirk Behme Acked-by: Miguel Ojeda Signed-off-by: Alexandre Courbot --- rust/kernel/num/bounded.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/rust/kernel/num/bounded.rs b/rust/kernel/num/bounded.rs index 2f5f13ecd3d6..d28d118abd8e 100644 --- a/rust/kernel/num/bounded.rs +++ b/rust/kernel/num/bounded.rs @@ -1101,3 +1101,24 @@ fn from(value: bool) -> Self { unsafe { Self::__new(T::from(value)) } } } + +impl Bounded +where + T: Integer + Zeroable, +{ + /// Converts this [`Bounded`] into a [`bool`]. + /// + /// This is a shorter way of writing `bool::from(self)`. + /// + /// # Examples + /// + /// ``` + /// use kernel::num::Bounded; + /// + /// assert_eq!(Bounded::::new::<0>().into_bool(), false); + /// assert_eq!(Bounded::::new::<1>().into_bool(), true); + /// ``` + pub fn into_bool(self) -> bool { + self.into() + } +} --=20 2.53.0 From nobody Thu Apr 2 20:26:43 2026 Received: from SJ2PR03CU001.outbound.protection.outlook.com (mail-westusazon11012059.outbound.protection.outlook.com [52.101.43.59]) (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 6BF761B4244; Sat, 14 Mar 2026 01:06:46 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.43.59 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450407; cv=fail; b=fQr/De0GKr3vITmeHfA60809xlGTrbyAytHa5hd66OOY+9JxZCOUyqdSROhiQf1eaYOqjf0//Mp1NE/x9B5E8htk1uYi5XywE/m/GDKAMtPy3EE832fbkdf0v1PL6evZAXuH32yMA/HDisrvtW+LJN3Mt3p3VH0dTnSbt03jHPI= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450407; c=relaxed/simple; bh=s1ZY5UjravxF6orXaQnV2BPeU9346o1GOVyeBfDj2+Y=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=VIhoj/4CQ7avXhin6O7EGHfKxVIMX+1ovVY6A5zkCJL5R9pIR/Lw70wL8VfaMzWsG/G14PKXpOAmS9Pa+CjVh5QkeLsD188QyynAT8K9TYEQTf7Bzjngj7XY6CAPT99e6hihihUiDpRGo4SVl07ldABpH9K7k6YTsn1N5ibMCZs= 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=uKysr7dr; arc=fail smtp.client-ip=52.101.43.59 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="uKysr7dr" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=F5kTAeWNIeal8qXZhUa5g6ri/2pfOfa+/obMC1lOuNyZavbnTpbHfgEIMGDf7nE4qYruQ5e8rgxIJUvRkmWHxz/CqXEfkGz7n7klPBD2X9jmjVYuNXfNQtXJbfUJHRcUkeC5BYlLWYB8poMPDDMObHHoXAARrHy80L4utVxGK0ZpOF86uNeJHVxMUlNORb8E9dbRAA5mn50oBxma5ttGTTFuKN5d8lL41MUuBwnkGf/9/+7n4v4u8MfyOQ3RlAZmeAw1KP7DBlA/4khCO5sMw5EyOwUZFaYvK++QI25TA78fiDHqMoPqJM2hsUDblfleL/+HmCIwXDrHQPp+x8YBAw== 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=zDdXjlcBiC5X5uW1KKVSvdZBRIiMUXuzKu+k7F5RJ5E=; b=HTIiKX+U5/o2NlbkBeNN0B4KyB2K/VT9pCo7MboE8jBf7co5nkpR8ZFUTEYYAMzx/nN7RprJGPbKdZ7nqRXwWaMY42X1ZedRosVaUvOX3+KGts3Vh4caaJodhX5kguyUPmJ3HeDigLWqnke8plhdN+WQ3MFHs9vzFip4bTyPYk781l5yrqhff5IMWfGNyidG8EGTnsyTeKcK1qadP1WBSLpzIo4llIobURQC03d7ko1R2ZkRbUXEfTJhrnPwFktdipBCqE3bMmk4bMU/YoTHGZKPVdSd822+J5UihY2GNTiInMEhC1tC1RsqCsxj3c96L4iZyuxtIuR5dRIpG+SFnQ== 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=zDdXjlcBiC5X5uW1KKVSvdZBRIiMUXuzKu+k7F5RJ5E=; b=uKysr7drV1tac1i+BWdDlcny2aTHh4sDXZBEHoatdL1jf02X2F495uH/aPJ4mFSef2d8UF7N2cKJ1i8aJ0IIXROnGCSF3Bbrfop1lPsATMiYket1x6rgi8Kcau3WVTDjBstWirJwIBPWL2q/TQi3KiqhCixDbQgBDSVuw7KIwgxq9vMAM7lTfe4pG1mKzAFxD5sPGEaJRexnWtpZg8QejmSmk+SgacVqb1L0ZLrsQCyUlGKcWBktb1qtYTNi77+KhblGFZsK47EvRuLViZtLCwKlfJqkpg3/rEYkuVmMEdvcjS9rn33KvffxUzumjreYOy+WV/1bv7XhJF7BUSDt6Q== 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 BY5PR12MB4033.namprd12.prod.outlook.com (2603:10b6:a03:213::22) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9723.6; Sat, 14 Mar 2026 01:06:43 +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.9723.000; Sat, 14 Mar 2026 01:06:43 +0000 From: Alexandre Courbot Date: Sat, 14 Mar 2026 10:06:14 +0900 Subject: [PATCH v9 04/10] rust: num: make Bounded::get const Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260314-register-v9-4-86805b2f7e9d@nvidia.com> References: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> In-Reply-To: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> To: Danilo Krummrich , Alice Ryhl , Daniel Almeida , Miguel Ojeda , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Boqun Feng Cc: Yury Norov , John Hubbard , Alistair Popple , Joel Fernandes , Timur Tabi , Edwin Peer , Eliot Courtney , Dirk Behme , Steven Price , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alexandre Courbot X-Mailer: b4 0.14.3 X-ClientProxiedBy: TYWPR01CA0019.jpnprd01.prod.outlook.com (2603:1096:400:aa::6) 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_|BY5PR12MB4033:EE_ X-MS-Office365-Filtering-Correlation-Id: 01166557-f723-42ed-55a5-08de8165f4bf X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|376014|7416014|10070799003|921020|22082099003|56012099003|18002099003; X-Microsoft-Antispam-Message-Info: 9k6nqCCzjqXydTxut30RSos3c9uKQ63xEYUkNtb7KHPlz4yzzknHwGWHneQVVOk6gI3cO16xRWmIK/33rApb7pL1LpLtZbkwTq5jPb0vpaqNTG9A1bcf3+P7M1MykZphpBiYvwFlMSgU75LiJSCQd/Ew4OGUuioA/Ko+D52CmV0I5gByIpiYUJHHyBtg4kjOP3BshNaSoGRDJv5QE107+OQniPdjBvjI8eK86VREdtj3eWKSv1dZEe1HEMicRUunPi48hSXVorQd8P99BephxwnU6M2s5Ui3uPaA/neeulXocFDxvRGT5aVBHE6pK9DFO8jl2m/78nWeTTBK8PPzXHbpKEuY2CaOxAf01IgqZHSHQbKk3sX8sPK/drqaJn/NJ3UC3RMZdv3FyK6AgwPyBnV5k4LfPgf+BCtDXb/3UqDqFj0EtCuPf7owS+Yuh4Bw8TWPJ982YNftTZ+90eFVzkKzG/Ifwq223XD5On+5ilmF6OJQII0pnZG+XjZrnR4vnSxvuYP4S7pUoRx8SJBWVCIePr6ftPWm1Lu3xZG9Ey0gBYtCyrWeezojCcRVCLqfdHQAVYa1imC1TCaQof+ivgQEkECjREc5xz/lf0AY9MYIqeba4IlvgsZ8tCTNfqHGVvOuD0ukozGVeTle6nl43LGnA1517841h5MUXxZUdxm9sikvxKDj1l+TI7OOXBnQ5hjZZtXmCXLYQAqZqevktDDMHQLW21Osid8nGGp3hfSAMmB4p3jweN1Ia/SqUBzOxQCO4FtWT5eCybAkOixC5A== 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)(366016)(1800799024)(376014)(7416014)(10070799003)(921020)(22082099003)(56012099003)(18002099003);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 2 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?RkhwVVFxckZkOCt5S1dXVEpmMGNaTHpsNzNPV1M3QXYwa1NFd2w4bTVKNzUz?= =?utf-8?B?dXkrQ3lTZ3lLemM2eW4zOGFEcHEzWkVYNDZiTGJiL0NxSkNsdzFSOGwrT1NB?= =?utf-8?B?UDVDSFBvQml0eUFvYys3Ui8xSE83aFBjRlZrRWtHb0dFUWp4N29mVjZBMmF2?= =?utf-8?B?RXpVd1Yxa0dab0pFYVlqVWVsOWsxK3ZEM21KbEVydmd3Z3o3akdrZTlVTytQ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xaGFTc0hSeExaOFZU?= =?utf-8?B?dk5VWitJaTZGajBJVHZZK3pHZEhUK0V2RitJY0ZZa1dBR2k0cm5FTHA5eVAz?= =?utf-8?B?cVY3NmZwSVJDKzJmdWduNjVWaFk1c3VTSGlZM0s4OVlXSHpyN3JQdjZIQU5l?= =?utf-8?B?SGdHN3pmaGNJUWNveGlhdEhxZ2VHK09sYTZOZi8veFZxbldUbFBXVDFZY3dV?= =?utf-8?B?ZVZyUWp5ZU9POElyZFdtcmw2cVpGV1l4Ui9talJzL2h4TXVaMzZ2ZEtSQjl0?= =?utf-8?B?R0g4TkFGMDBiRTQ2SndzVDQvTEFWbVo0Z3JveFRrZUs0NkFzeWRsZTdqY2pF?= =?utf-8?Q?NvfrMCba+nvdZCipfum5VClhs8aQG7ldmGP9kwSRZfrDU?= X-MS-Exchange-AntiSpam-MessageData-1: l95YpV1GDbOrag== X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 01166557-f723-42ed-55a5-08de8165f4bf X-MS-Exchange-CrossTenant-AuthSource: CH2PR12MB3990.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 14 Mar 2026 01:06:43.4214 (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: Q+9SPRkmRf4jv8SVwBd+229a1QNqEsIU3tbKUiMxCj+BYBrTPETAaMwH+Juq8AcvGz8umm1kmiLi5Eps9lG2nw== X-MS-Exchange-Transport-CrossTenantHeadersStamped: BY5PR12MB4033 There is a need to access the inner value of a `Bounded` in const context, notably for bitfields and registers. Remove the invariant check of `Bounded::get`, which allows us to make it const. Reviewed-by: Gary Guo Signed-off-by: Alexandre Courbot --- rust/kernel/num/bounded.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/rust/kernel/num/bounded.rs b/rust/kernel/num/bounded.rs index d28d118abd8e..bbab6bbcb315 100644 --- a/rust/kernel/num/bounded.rs +++ b/rust/kernel/num/bounded.rs @@ -379,6 +379,9 @@ pub fn from_expr(expr: T) -> Self { =20 /// Returns the wrapped value as the backing type. /// + /// This is similar to the [`Deref`] implementation, but doesn't enfor= ce the size invariant of + /// the [`Bounded`], which might produce slightly less optimal code. + /// /// # Examples /// /// ``` @@ -387,8 +390,8 @@ pub fn from_expr(expr: T) -> Self { /// let v =3D Bounded::::new::<7>(); /// assert_eq!(v.get(), 7u32); /// ``` - pub fn get(self) -> T { - *self.deref() + pub const fn get(self) -> T { + self.0 } =20 /// Increases the number of bits usable for `self`. --=20 2.53.0 From nobody Thu Apr 2 20:26:43 2026 Received: from SJ2PR03CU001.outbound.protection.outlook.com (mail-westusazon11012061.outbound.protection.outlook.com [52.101.43.61]) (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 D3F61242D60; Sat, 14 Mar 2026 01:06:50 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.43.61 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450412; cv=fail; b=bu3DWqNHh6k05PplD6YRxjYVgcVGJnn+I1wMVAnEH3yGhMTWysd8kgFViwKY4EQvSN/hwNfsfonpbJQp6Q7EcfFakGxKGstnwJmh2uw1e8qRO64WJhP+ddl95EJzur7Polqhhz0q0YwMCwaST3wPe9ZrUVggG4PiRFnz7k9kJWo= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450412; c=relaxed/simple; bh=Be6i/LAWzJb3H5rLICjYFOzv1Z3ybi5aWcJSmZNItSE=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=molxlcpDW9Yr/frY+boLi87N/ZY9gtzh9URRythTbQXcw7jRBDDmo04GxQcb4WmmNNwJCJwa6OEWXtsq2gw00SGxSZw07Q+TUdnmdujnkzSvrlJNCqbudf0DUImoYj6mY+MXGQccokNSIDNGiZYuX2PknCTTPftQhxCaiXHyA2A= 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=JPY4byY3; arc=fail smtp.client-ip=52.101.43.61 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="JPY4byY3" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=FjDPVpI9QkZC62J1W5Yxq3LXs8ct/7dG/T/2a8AOjnc9YXMMtbkKSy/d9/ImU9g/LEFJWw5pDs7+QzvknQc40LUMDrO973HgE5do2FW66wRQcBvLajCO4seJxxLm00rIAr3V9rzcyp/qpgclAA/fa6IOBfb+Rr0FXrbFlKYACK1ynQvsVUKeuiJq2mB5yot5IM1XF+FsLzK67KrE5HJirD6TN8oOx9VXYtRhubv9M9rySP8UjXoCOp6AmZF9jgvdjGDK5og/nriB3uikkYREtEjA0ntJ21ezGQlTuXIyGn7XJbqXyC13PqNxZuVtchJil3qW3kytWav1McnKh+O2XA== 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=DYyB57HzUZsex5eIfTQsMEr5ONVaNyUU4s54AQiE3Zc=; b=MBnHO0gS7D3OKKi3pqZKcnQc+dcvqEL9tRJLHRFKTY1IztqLsj9RGruI1WpqOg0VWdywJattQkd2sJY5xxm0/XHDMUANk1YVOwtcM8Fxw8MZPOd6NN9EEIATeoKlShxuVfa9qIRYMgurv//XC8wQc5LQrYfxynXm8bJup+pba3Yi/Wk5jR8yxIWLXLqb3S6Ys6o9m/xf895KBMAUQSesOeqgIulg0kbfjDBLKRfojk3YcRmwesGCZIAwvRBK4gdIX39DcGdj5GX1H9xrD6ETh/8f4uUVvDfCt09UXaixsJ8ESyMQsB2qoj707xim+fmOl/yvIuYW+RNL3C+cNSbc1w== 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=DYyB57HzUZsex5eIfTQsMEr5ONVaNyUU4s54AQiE3Zc=; b=JPY4byY3IVBWmSz8Hm8rTt9kCRSQcv6U7f57wq++unuH1DiTIppsI5AQ97g17Bph2kdvsou2dFU5Hxd1fsVZgr1dK9ie+x4Ok3tzPpothy1oK10sJx1Kko1CrMHNKl1WaPq8/cSrZ2sSMyyyrgYtz+IodK8xIqRSKhE3V3PRNv9qVkx5LX/g4w6WzP8YywkhbXTjWcvfUYeTubf9RV9aY2B0RnZhzPPkAAwffPUettYuud7+3zU0QyyeIvdFmmWuHaKhO2yyt/TxEhQTCzlA2sG+bXsN/KD5ZJ1AYWlXAz0abxDf9Hojoahj2ZgPHhg/IvWCuRuCi6VnLw9EWzr9DQ== 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 BY5PR12MB4033.namprd12.prod.outlook.com (2603:10b6:a03:213::22) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9723.6; Sat, 14 Mar 2026 01:06:47 +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.9723.000; Sat, 14 Mar 2026 01:06:47 +0000 From: Alexandre Courbot Date: Sat, 14 Mar 2026 10:06:15 +0900 Subject: [PATCH v9 05/10] rust: io: add IoLoc type and generic I/O accessors Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260314-register-v9-5-86805b2f7e9d@nvidia.com> References: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> In-Reply-To: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> To: Danilo Krummrich , Alice Ryhl , Daniel Almeida , Miguel Ojeda , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Boqun Feng Cc: Yury Norov , John Hubbard , Alistair Popple , Joel Fernandes , Timur Tabi , Edwin Peer , Eliot Courtney , Dirk Behme , Steven Price , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alexandre Courbot X-Mailer: b4 0.14.3 X-ClientProxiedBy: TYXPR01CA0044.jpnprd01.prod.outlook.com (2603:1096:403:a::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_|BY5PR12MB4033:EE_ X-MS-Office365-Filtering-Correlation-Id: 3ad6f8fc-24e7-4a4e-1c7e-08de8165f768 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|376014|7416014|10070799003|921020|22082099003|56012099003|18002099003; X-Microsoft-Antispam-Message-Info: ezPcn+wF/E7wzMEoP1DN5utTJewPmVZKSBeYyCBxUBxE0P20lfpXV0WAgbiLELw5gpx3Bgye3c4vCN5DJxgL/llzpPXF/zgk6Nn9x5Lh8l3hm1a0H+o92HB8MlsQ1wFaS77aDeB922BvOOCFgRuHiRhsY6wnv0fFw+tO2C4px9QzBkCEUhRJi2/piDfmyFOdbc/Ge7dj+/7jpCLN2ZMGvlTV0g4rcukqLrhARo/eySOe+oFmYuRZJMNX8f31yxPlgTCoY/VztqYIhySAO5KqggHyIG840wgd3xvVghZP8R+25nUR+qEN20wQX0vxhGzt7jSqWQNqJIwuhe80dspxHhDVFBa4tc2/MD52dyrHiVBn4cXcGV+SOQeClj3/Z1Q//zGIB+RKk7GpGv9XLQ9vdJvo++FVPkeaX0e8ylVoznFfpfyIdLP8d3cuvzvOIXs7O9hKyp138OZ+7gC71SDxSQ/6Owe6/ZxkqsL9Se2XEe2rp2xvH7Y/lkyLa3t7udhP2pf8e/arB086dY/7jbAtDzCzWfRk+Obnf9O6/sM/X2POET2VITn0dEm2yzviW0Z5oBZtN4LSRXf1sSGBc64JR04GTIB0S6u43XV5xdJb5D+ClR1I9jYw1PNHUgGej4b1W/K5POegJRbObbwa9HcEVsNIVwWQP5nKVzwY1QsOvhy/1srWKXCDcNEUdkOjxjF6087jeI99KcqCzncm0jrubrPiVrjUt3UHohxYn5F5EuviZzdCfq6cb5Q0bquQK2tN3C27tbV4P11frYzeS6QKVw== 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)(366016)(1800799024)(376014)(7416014)(10070799003)(921020)(22082099003)(56012099003)(18002099003);DIR:OUT;SFP:1101; X-MS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1hEYXFWMFI3UHU4OU9Z?= =?utf-8?B?NTJrdStQUE9HdHhlY2o2RG1BblZiT2s2VW1pMWtOZzBxNE5CeWNYY0d2OVF2?= =?utf-8?B?RHIzT0hDZjR2c094VmNtaFo0SitYam1tQlVnR0tQbU1jN0NtelZlSUdHUzhR?= =?utf-8?B?V251WTU2eGkrMXhnNi9NL0ZFV3BtY3Z4S2Z3Wk1RWmpMaFpXRHNnN1FjRk5m?= =?utf-8?B?ZTJoN0tML3luNHRRVmk1M05jREVzdXBzVFM5N1RhdDNDMitpenh2OENDa09m?= =?utf-8?B?T01HNWY3elZ6bHgyR1N5a3NGS3lZZXVlTWF5dkpKYlJGNHAzdlNaZVAwMnhs?= =?utf-8?B?SjcvUFlybkFwcFpLQUNKNmFoWFJXQ04yaG9iQnlsaTZJdko3MmZnc2N5aXBL?= =?utf-8?B?R2dIeUpWa3dzN0lYZzUvVzRqWXdJK000dlVYc2VWUVQ2cWtMZ0VzY1lRVlV0?= =?utf-8?B?SW41bjBzNERxTEt1N2dJWWZ0bWlrUldHZjVYWU9tMVkycCtHb0lnTE5sd0lr?= =?utf-8?B?dWZUVDJKa2FoVXo0S0FwTnBHRCtyRFBwSWoxcDVCS2JIQ2t5YTJUUU82R2tr?= =?utf-8?B?Z3JXVXBHbUdxaVNWc1FOTHFrVmlNMUREdHFFVktEVlNNSmptM3BVZUtla0R2?= =?utf-8?Q?sBn7f81G+jXNRs8PL5XwRUiPTC01hJCdpndP1Gnzq61VE?= X-MS-Exchange-AntiSpam-MessageData-1: woRL+Zne728nVA== X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 3ad6f8fc-24e7-4a4e-1c7e-08de8165f768 X-MS-Exchange-CrossTenant-AuthSource: CH2PR12MB3990.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 14 Mar 2026 01:06:47.7097 (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: DLrfzaCZ/AN3xWvlllyC2FhbnzUH0WqPZjdmvZ6Q70Hy+u2nPk0O4BKT/WfX7bqJqH5fh4MJ1RwGXqpdH5RmoQ== X-MS-Exchange-Transport-CrossTenantHeadersStamped: BY5PR12MB4033 I/O accesses are defined by the following properties: - An I/O location, which consists of a start address, a width, and a type to interpret the read value as, - A value, which is returned for reads or provided for writes. Introduce the `IoLoc` trait, which allows implementing types to fully specify an I/O location. This allows I/O operations to be made generic through the new `read` and `write` methods. This design will allow us to factorize the I/O code working with primitives, and to introduce ways to perform I/O with a higher degree of control through register types. Co-developed-by: Gary Guo Signed-off-by: Gary Guo Signed-off-by: Alexandre Courbot --- rust/kernel/io.rs | 124 ++++++++++++++++++++++++++++++++++++++++++++++++++= ++++ 1 file changed, 124 insertions(+) diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index b150743ffa4f..e7e32f921efb 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -173,6 +173,30 @@ pub trait IoCapable { unsafe fn io_write(&self, value: T, address: usize); } =20 +/// Describes a given I/O location: its offset, width, and type to convert= the raw value from and +/// into. +/// +/// This trait is the key abstraction allowing [`Io::read`], [`Io::write`]= , and [`Io::update`] (and +/// their fallible [`try_read`](Io::try_read), [`try_write`](Io::try_write= ) and +/// [`try_update`](Io::try_update) counterparts) to work uniformly with bo= th raw [`usize`] offsets +/// (for primitive types like [`u32`]) and typed ones. +/// +/// An `IoLoc` carries three pieces of information: +/// +/// - The offset to access (returned by [`IoLoc::offset`]), +/// - The width of the access (determined by [`IoLoc::IoType`]), +/// - The type `T` in which the raw data is returned or provided. +/// +/// `T` and `IoLoc::IoType` may differ: for instance, a typed register has= `T` =3D the register type +/// with its bitfields, and `IoType` =3D its backing primitive (e.g. `u32`= ). +pub trait IoLoc { + /// Size ([`u8`], [`u16`], etc) of the I/O performed on the returned [= `offset`](IoLoc::offset). + type IoType: Into + From; + + /// Consumes `self` and returns the offset of this location. + fn offset(self) -> usize; +} + /// Types implementing this trait (e.g. MMIO BARs or PCI config regions) /// can perform I/O operations on regions of memory. /// @@ -406,6 +430,106 @@ fn write64(&self, value: u64, offset: usize) // SAFETY: `address` has been validated by `io_addr_assert`. unsafe { self.io_write(value, address) } } + + /// Generic fallible read with runtime bounds check. + #[inline(always)] + fn try_read(&self, location: L) -> Result + where + L: IoLoc, + Self: IoCapable, + { + let address =3D self.io_addr::(location.offset())?; + + // SAFETY: `address` has been validated by `io_addr`. + Ok(unsafe { self.io_read(address) }.into()) + } + + /// Generic fallible write with runtime bounds check. + #[inline(always)] + fn try_write(&self, location: L, value: T) -> Result + where + L: IoLoc, + Self: IoCapable, + { + let address =3D self.io_addr::(location.offset())?; + let io_value =3D value.into(); + + // SAFETY: `address` has been validated by `io_addr`. + unsafe { self.io_write(io_value, address) } + + Ok(()) + } + + /// Generic fallible update with runtime bounds check. + /// + /// Note: this does not perform any synchronization. The caller is res= ponsible for ensuring + /// exclusive access if required. + #[inline(always)] + fn try_update(&self, location: L, f: F) -> Result + where + L: IoLoc, + Self: IoCapable, + F: FnOnce(T) -> T, + { + let address =3D self.io_addr::(location.offset())?; + + // SAFETY: `address` has been validated by `io_addr`. + let value: T =3D unsafe { self.io_read(address) }.into(); + let io_value =3D f(value).into(); + + // SAFETY: `address` has been validated by `io_addr_assert`. + unsafe { self.io_write(io_value, address) } + + Ok(()) + } + + /// Generic infallible read with compile-time bounds check. + #[inline(always)] + fn read(&self, location: L) -> T + where + L: IoLoc, + Self: IoKnownSize + IoCapable, + { + let address =3D self.io_addr_assert::(location.offset()= ); + + // SAFETY: `address` has been validated by `io_addr_assert`. + unsafe { self.io_read(address) }.into() + } + + /// Generic infallible write with compile-time bounds check. + #[inline(always)] + fn write(&self, location: L, value: T) + where + L: IoLoc, + Self: IoKnownSize + IoCapable, + { + let address =3D self.io_addr_assert::(location.offset()= ); + let io_value =3D value.into(); + + // SAFETY: `address` has been validated by `io_addr_assert`. + unsafe { self.io_write(io_value, address) } + } + + /// Generic infallible update with compile-time bounds check. + /// + /// Note: this does not perform any synchronization. The caller is res= ponsible for ensuring + /// exclusive access if required. + #[inline(always)] + fn update(&self, location: L, f: F) + where + L: IoLoc, + Self: IoKnownSize + IoCapable + Sized, + F: FnOnce(T) -> T, + { + let address =3D self.io_addr_assert::(location.offset()= ); + + // SAFETY: `address` has been validated by `io_addr_assert`. + let value: T =3D unsafe { self.io_read(address) }.into(); + let io_value =3D f(value).into(); + + // SAFETY: `address` has been validated by `io_addr_assert`. + unsafe { self.io_write(io_value, address) } + } } =20 /// Trait for types with a known size at compile time. --=20 2.53.0 From nobody Thu Apr 2 20:26:43 2026 Received: from BN8PR05CU002.outbound.protection.outlook.com (mail-eastus2azon11011059.outbound.protection.outlook.com [52.101.57.59]) (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 280AC2517A5; Sat, 14 Mar 2026 01:06:55 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.57.59 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450417; cv=fail; b=dVhA32GBqgFu3eaL1u4V86lhFIFI1DCrMyvSCYeLYj2HbdMA/P1PgamiGpFd5oN7aergh7cW2Qfak9W56bQRqwacoElfSd8OxvYNWdgSeswFH3ZXkhpMvQcKk/R+wAL1XmmZGjdtWCi2NOFhtR1VnrBk1xFAh4iSbxICcs6TC+g= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450417; c=relaxed/simple; bh=8se6tM1SnAQB4KBKef+i0ndmBW3rc5y+8v/P03v7LLM=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=XEaDjWQUzDHg9dbYinX42EojeypRVIGsbcNRR0IMRcezLzLnmFat1ZJx6iFRi2rXgUX1TS9N4oqdplzT8G+Wx7D575SzRYX9QbuMcZrD0mlCgclodScDBqnQIBJGvALzkMQHuNlX/l7PKrOlx3jgendcqivGwMlHdxIqdzeQ7MA= 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=L+fvQPrA; arc=fail smtp.client-ip=52.101.57.59 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="L+fvQPrA" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=r51qDny8Lz0vtE9yKW/3bzqcP2FigS8+2gIq73Bxh2ZH516IU2Pt7LBm/3Nbss58KcWTxlyRm58mLKjq+UWjFd2iJQ913zPbYOyaw3Wp2OJXYyh1wnuNxrQghvG8UPypamtp0TGSIadiEPJ47BkUkM9MgUjOjUW5SjjxzjCBGxbTjCLtYx6/pcMnbWNBIAv1VESnaI4kZ+hUA88NHWR9inA7bqkzSI1zY1ux6EETYkiwvAxrT4EhyjsMTUKNXrsXWlUcsFu3TyhWKcqD48nQ9yG4NhmsLvaFy7b+GVW32QvLNd9r66dNXXZIjJ1hZ8BDupdsZSiu5YbOTGMkpkKRSA== 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=plts2w1j13B/V544+z+lhv+EUY6uBSOLs+JhOcBxnMM=; b=DRxhphWkaconNh27Vuie7CNnKUkWy8t4JwnU7FZ3va/VnEaqy9dmde4SegDIKvPB3t+fS1nWz9SBpQYNxo88zZrHD9rTq9oxSe3ayY1xSfQ0eFlxhBgqWSaODS0aIIrvhDVUd8r4QqT3tp4N9hULk0VlKsnbsoLzdH5JItR1pTVs+O4MiRU/R6cRJO3+m6nf39acXm2HSAyqeug99CmNxadcyw2/SJ0sUBijyR3w8IOMNFymKzL/9xGnCqsM2LIXvQKI6SOnW9JhgqRYir0Ap5E9zwzqr6AAHQcrDvpbCqATpng6QQDGXs4fu5ribHf62VG/jq+UF+MFf9KJgh0aOw== 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=plts2w1j13B/V544+z+lhv+EUY6uBSOLs+JhOcBxnMM=; b=L+fvQPrA5tmXo90HCzKz1CFwjMk+jedkPu8IbxCk0XIWNr7p5Vok4mzRLoATLTHlanZZSKcbnObTdIWwiKT7j8KgK0ZmP/tw/IAnZOy9wA4O/b+brbURg/KihBFPtT2sGsFtoFSDzWtUe1Ip8hcx3BRhPNd9wxFnj8RmR69puB3M7xKL7CFs1xhIRSpgqqfagh3iMBubg9ySNwESGpGyFJrSXN1mYIXmB1mSnVMFz1V+pNZS9IpAtMmoKkopC7l2nQ+4/68Pn81npBL4tfNDChjqJ+qzEAbp/+HjN4xvfwS9NvPdAnf69NLXFvWbhlzwQ8txnyriHGvYqEkP5IOqag== 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 BY5PR12MB4033.namprd12.prod.outlook.com (2603:10b6:a03:213::22) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9723.6; Sat, 14 Mar 2026 01:06:51 +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.9723.000; Sat, 14 Mar 2026 01:06:51 +0000 From: Alexandre Courbot Date: Sat, 14 Mar 2026 10:06:16 +0900 Subject: [PATCH v9 06/10] rust: io: use generic read/write accessors for primitive accesses Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260314-register-v9-6-86805b2f7e9d@nvidia.com> References: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> In-Reply-To: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> To: Danilo Krummrich , Alice Ryhl , Daniel Almeida , Miguel Ojeda , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Boqun Feng Cc: Yury Norov , John Hubbard , Alistair Popple , Joel Fernandes , Timur Tabi , Edwin Peer , Eliot Courtney , Dirk Behme , Steven Price , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alexandre Courbot X-Mailer: b4 0.14.3 X-ClientProxiedBy: TY4P301CA0071.JPNP301.PROD.OUTLOOK.COM (2603:1096:405:36f::10) 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_|BY5PR12MB4033:EE_ X-MS-Office365-Filtering-Correlation-Id: 96e362c3-83bd-4f90-1b0c-08de8165f9b1 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|376014|7416014|10070799003|921020|22082099003|56012099003|18002099003; X-Microsoft-Antispam-Message-Info: 2ag4lAl9I4fCgka5M7o5eHR2lu8pO5MB7qDt+NByd+p7XsPB5N4uflA/u9jGmpNtVde2mrMOvM+cmvj0ezEnbJWIy0HmBny/Xi4sHS3LmESpbANedqoKp2g/h1wXK+nqqz/N69RWcll00V7sfJQwVX/PF2vUZoeBFKJ9qwxIhTvp0EaOV9TRPU0F3z5ZkiW7Lo8vcJqpuBmMRBTjrygF4poZgTwfxsKcNWUGZpaDg4/zT0UvBDIsx3RV0nTk71TlwY0grf5xHCffjyy8wmzp2AS39PO8KMhf9qRNY79IvbW/lcAhMuzwZH42C9Lt8fbk+DzBoaESSV/or80AxyEwlNLCUFIx++9QG6v208mdOUHV5M0mAMZeJ2oocfMG0KUNUpfsKtabJv6lpVGaGqSBo2G/Y1RMCEQcp1L7XzZCJ0RZD3NybTEokv0A2yl3qC658mbVF4EkowavHlb6tC73Ntt/+iaz4CrnqK47SIKJ14HwIqKlmJGgRGyzKAl2V7O94/E/mO1D85ynSVh/r2ZkUczRNo6El5zBSVm/C15AJpUpp3f+AJiG78+Cc2fRMs0vJ9+h9Qo2t/Ngs0PlyuMwi3StKbB/7MQY7mOsIAA6Mg3voHOuWcRB269WknurxL90HStZh//6pEqgCsIM0f8rzPaU4DXW3fI5g6t/6z/aZKgSXh6k032gi20O/q6twBdpv80rIKTE1VAVjuq7ppXe8H9P61EYCH7aubuDXqQEuRuu4lj7f1+eWWerX69FhgshRfiafMWZ4zSVVa1A6MGBmA== 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)(366016)(1800799024)(376014)(7416014)(10070799003)(921020)(22082099003)(56012099003)(18002099003);DIR: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RklMUmxKaUkxSnFWTkpoSFFicC9uSVV0?= =?utf-8?B?R3ZpckNjS0svLzl0eWVFWWlyQUxlUkZmMlFNYm8rN21uOGRnT2NaY2lZTExW?= =?utf-8?B?aStySitZbDlOQkxBNmVlaFZXRG5HbnRqd3p5aU51YjZabEZrK0dTelhEaUtK?= =?utf-8?B?VGkzOG1ndXpiOENDNEh6MWpNbS8ydGVPNEpndVByeHNjK2Qza1RucWxaaUlz?= =?utf-8?B?MDNNWEE4bzB2d0cvSzhvOEc1M2EzN3N0UU9hUUIwdXI1R1p4dDc4RTBMNXRs?= =?utf-8?B?TGpRM1ZCV3c5cUlqUU5NbytCcU4vUjNHTklPbnBZUGkzVlBNYUZzWUh2RytB?= =?utf-8?B?RDgwc3lrR2xCeEE0Uk5GVHl4TVVhMGkwcHJCOGgrNjdpZWd0elk5TG82TTRO?= =?utf-8?B?Y0FVbHFCd3JCZ2l3bFpBUHZEOHFvKzNLM1YvVkhyaG1VZVpjbTlKTW9maFlC?= =?utf-8?B?KzVUVUNvc3AxNFlhMXRWUHNLNHJFSUx4eENEWUhZRFFoV05YYTRBSHY3SUlu?= =?utf-8?B?dTBCQTJndXZwMkQwSG9ZeVBnOFdZNENHWm9QQXFRTi9iMXhiUk1RZVJsY0NR?= =?utf-8?B?YUpTMVl3eVdmWlZoaXdHS2oxZkdiK09uY2F6MlFJWDAyemRkRUp5ZVg5Q3Fr?= =?utf-8?Q?PxNViNL4SE1peyZoLr+GDxtUAJWbvYKjVslxCKdyDEa+r?= X-MS-Exchange-AntiSpam-MessageData-1: Hx9E79Et+zQW9g== X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 96e362c3-83bd-4f90-1b0c-08de8165f9b1 X-MS-Exchange-CrossTenant-AuthSource: CH2PR12MB3990.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 14 Mar 2026 01:06:51.7231 (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: 1CjHsWLaeKReVANOml1HAtHNTkPPLy55Q+NUjR9TAnxTEw7PeiJAohU8MHq7I0rXL4X6ufAm+hja8MS6n7H7Gg== X-MS-Exchange-Transport-CrossTenantHeadersStamped: BY5PR12MB4033 By providing the required `IoLoc` implementations on `usize`, we can leverage the generic accessors and reduce the number of unsafe blocks in the module. This also allows us to directly call the generic `read/write/update` methods with primitive types, so add examples illustrating this. Signed-off-by: Alexandre Courbot Reviewed-by: Gary Guo --- rust/kernel/io.rs | 218 +++++++++++++++++++++++++++++++++++++-------------= ---- 1 file changed, 150 insertions(+), 68 deletions(-) diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index e7e32f921efb..c9d43b1372ab 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -197,6 +197,26 @@ pub trait IoLoc { fn offset(self) -> usize; } =20 +/// Implements [`IoLoc<$ty>`] for [`usize`], allowing to use `usize` as a = parameter of +/// [`Io::read`] and [`Io::write`]. +macro_rules! impl_usize_ioloc { + ($($ty:ty),*) =3D> { + $( + impl IoLoc<$ty> for usize { + type IoType =3D $ty; + + #[inline(always)] + fn offset(self) -> usize { + self + } + } + )* + } +} + +// Provide the ability to read any primitive type from a [`usize`]. +impl_usize_ioloc!(u8, u16, u32, u64); + /// Types implementing this trait (e.g. MMIO BARs or PCI config regions) /// can perform I/O operations on regions of memory. /// @@ -241,10 +261,7 @@ fn try_read8(&self, offset: usize) -> Result where Self: IoCapable, { - let address =3D self.io_addr::(offset)?; - - // SAFETY: `address` has been validated by `io_addr`. - Ok(unsafe { self.io_read(address) }) + self.try_read(offset) } =20 /// Fallible 16-bit read with runtime bounds check. @@ -253,10 +270,7 @@ fn try_read16(&self, offset: usize) -> Result where Self: IoCapable, { - let address =3D self.io_addr::(offset)?; - - // SAFETY: `address` has been validated by `io_addr`. - Ok(unsafe { self.io_read(address) }) + self.try_read(offset) } =20 /// Fallible 32-bit read with runtime bounds check. @@ -265,10 +279,7 @@ fn try_read32(&self, offset: usize) -> Result where Self: IoCapable, { - let address =3D self.io_addr::(offset)?; - - // SAFETY: `address` has been validated by `io_addr`. - Ok(unsafe { self.io_read(address) }) + self.try_read(offset) } =20 /// Fallible 64-bit read with runtime bounds check. @@ -277,10 +288,7 @@ fn try_read64(&self, offset: usize) -> Result where Self: IoCapable, { - let address =3D self.io_addr::(offset)?; - - // SAFETY: `address` has been validated by `io_addr`. - Ok(unsafe { self.io_read(address) }) + self.try_read(offset) } =20 /// Fallible 8-bit write with runtime bounds check. @@ -289,11 +297,7 @@ fn try_write8(&self, value: u8, offset: usize) -> Resu= lt where Self: IoCapable, { - let address =3D self.io_addr::(offset)?; - - // SAFETY: `address` has been validated by `io_addr`. - unsafe { self.io_write(value, address) }; - Ok(()) + self.try_write(offset, value) } =20 /// Fallible 16-bit write with runtime bounds check. @@ -302,11 +306,7 @@ fn try_write16(&self, value: u16, offset: usize) -> Re= sult where Self: IoCapable, { - let address =3D self.io_addr::(offset)?; - - // SAFETY: `address` has been validated by `io_addr`. - unsafe { self.io_write(value, address) }; - Ok(()) + self.try_write(offset, value) } =20 /// Fallible 32-bit write with runtime bounds check. @@ -315,11 +315,7 @@ fn try_write32(&self, value: u32, offset: usize) -> Re= sult where Self: IoCapable, { - let address =3D self.io_addr::(offset)?; - - // SAFETY: `address` has been validated by `io_addr`. - unsafe { self.io_write(value, address) }; - Ok(()) + self.try_write(offset, value) } =20 /// Fallible 64-bit write with runtime bounds check. @@ -328,11 +324,7 @@ fn try_write64(&self, value: u64, offset: usize) -> Re= sult where Self: IoCapable, { - let address =3D self.io_addr::(offset)?; - - // SAFETY: `address` has been validated by `io_addr`. - unsafe { self.io_write(value, address) }; - Ok(()) + self.try_write(offset, value) } =20 /// Infallible 8-bit read with compile-time bounds check. @@ -341,10 +333,7 @@ fn read8(&self, offset: usize) -> u8 where Self: IoKnownSize + IoCapable, { - let address =3D self.io_addr_assert::(offset); - - // SAFETY: `address` has been validated by `io_addr_assert`. - unsafe { self.io_read(address) } + self.read(offset) } =20 /// Infallible 16-bit read with compile-time bounds check. @@ -353,10 +342,7 @@ fn read16(&self, offset: usize) -> u16 where Self: IoKnownSize + IoCapable, { - let address =3D self.io_addr_assert::(offset); - - // SAFETY: `address` has been validated by `io_addr_assert`. - unsafe { self.io_read(address) } + self.read(offset) } =20 /// Infallible 32-bit read with compile-time bounds check. @@ -365,10 +351,7 @@ fn read32(&self, offset: usize) -> u32 where Self: IoKnownSize + IoCapable, { - let address =3D self.io_addr_assert::(offset); - - // SAFETY: `address` has been validated by `io_addr_assert`. - unsafe { self.io_read(address) } + self.read(offset) } =20 /// Infallible 64-bit read with compile-time bounds check. @@ -377,10 +360,7 @@ fn read64(&self, offset: usize) -> u64 where Self: IoKnownSize + IoCapable, { - let address =3D self.io_addr_assert::(offset); - - // SAFETY: `address` has been validated by `io_addr_assert`. - unsafe { self.io_read(address) } + self.read(offset) } =20 /// Infallible 8-bit write with compile-time bounds check. @@ -389,10 +369,7 @@ fn write8(&self, value: u8, offset: usize) where Self: IoKnownSize + IoCapable, { - let address =3D self.io_addr_assert::(offset); - - // SAFETY: `address` has been validated by `io_addr_assert`. - unsafe { self.io_write(value, address) } + self.write(offset, value) } =20 /// Infallible 16-bit write with compile-time bounds check. @@ -401,10 +378,7 @@ fn write16(&self, value: u16, offset: usize) where Self: IoKnownSize + IoCapable, { - let address =3D self.io_addr_assert::(offset); - - // SAFETY: `address` has been validated by `io_addr_assert`. - unsafe { self.io_write(value, address) } + self.write(offset, value) } =20 /// Infallible 32-bit write with compile-time bounds check. @@ -413,10 +387,7 @@ fn write32(&self, value: u32, offset: usize) where Self: IoKnownSize + IoCapable, { - let address =3D self.io_addr_assert::(offset); - - // SAFETY: `address` has been validated by `io_addr_assert`. - unsafe { self.io_write(value, address) } + self.write(offset, value) } =20 /// Infallible 64-bit write with compile-time bounds check. @@ -425,13 +396,31 @@ fn write64(&self, value: u64, offset: usize) where Self: IoKnownSize + IoCapable, { - let address =3D self.io_addr_assert::(offset); - - // SAFETY: `address` has been validated by `io_addr_assert`. - unsafe { self.io_write(value, address) } + self.write(offset, value) } =20 /// Generic fallible read with runtime bounds check. + /// + /// # Examples + /// + /// Read a primitive type from an I/O address: + /// + /// ```no_run + /// use kernel::io::{ + /// Io, + /// Mmio, + /// }; + /// + /// fn do_reads(io: &Mmio) -> Result { + /// // 32-bit read from address `0x10`. + /// let v: u32 =3D io.try_read(0x10)?; + /// + /// // 8-bit read from address `0xfff`. + /// let v: u8 =3D io.try_read(0xfff)?; + /// + /// Ok(()) + /// } + /// ``` #[inline(always)] fn try_read(&self, location: L) -> Result where @@ -445,6 +434,27 @@ fn try_read(&self, location: L) -> Result } =20 /// Generic fallible write with runtime bounds check. + /// + /// # Examples + /// + /// Write a primitive type to an I/O address: + /// + /// ```no_run + /// use kernel::io::{ + /// Io, + /// Mmio, + /// }; + /// + /// fn do_writes(io: &Mmio) -> Result { + /// // 32-bit write of value `1` at address `0x10`. + /// io.try_write(0x10, 1u32)?; + /// + /// // 8-bit write of value `0xff` at address `0xfff`. + /// io.try_write(0xfff, 0xffu8)?; + /// + /// Ok(()) + /// } + /// ``` #[inline(always)] fn try_write(&self, location: L, value: T) -> Result where @@ -464,6 +474,23 @@ fn try_write(&self, location: L, value: T) -> Re= sult /// /// Note: this does not perform any synchronization. The caller is res= ponsible for ensuring /// exclusive access if required. + /// + /// # Examples + /// + /// Read the u32 value at address `0x10`, increment it, and store the = updated value back: + /// + /// ```no_run + /// use kernel::io::{ + /// Io, + /// Mmio, + /// }; + /// + /// fn do_update(io: &Mmio<0x1000>) -> Result { + /// io.try_update(0x10, |v: u32| { + /// v + 1 + /// }) + /// } + /// ``` #[inline(always)] fn try_update(&self, location: L, f: F) -> Result where @@ -484,6 +511,25 @@ fn try_update(&self, location: L, f: F) -> Re= sult } =20 /// Generic infallible read with compile-time bounds check. + /// + /// # Examples + /// + /// Read a primitive type from an I/O address: + /// + /// ```no_run + /// use kernel::io::{ + /// Io, + /// Mmio, + /// }; + /// + /// fn do_reads(io: &Mmio<0x1000>) { + /// // 32-bit read from address `0x10`. + /// let v: u32 =3D io.read(0x10); + /// + /// // 8-bit read from the top of the I/O space. + /// let v: u8 =3D io.read(0xfff); + /// } + /// ``` #[inline(always)] fn read(&self, location: L) -> T where @@ -497,6 +543,25 @@ fn read(&self, location: L) -> T } =20 /// Generic infallible write with compile-time bounds check. + /// + /// # Examples + /// + /// Write a primitive type to an I/O address: + /// + /// ```no_run + /// use kernel::io::{ + /// Io, + /// Mmio, + /// }; + /// + /// fn do_writes(io: &Mmio<0x1000>) { + /// // 32-bit write of value `1` at address `0x10`. + /// io.write(0x10, 1u32); + /// + /// // 8-bit write of value `0xff` at the top of the I/O space. + /// io.write(0xfff, 0xffu8); + /// } + /// ``` #[inline(always)] fn write(&self, location: L, value: T) where @@ -514,6 +579,23 @@ fn write(&self, location: L, value: T) /// /// Note: this does not perform any synchronization. The caller is res= ponsible for ensuring /// exclusive access if required. + /// + /// # Examples + /// + /// Read the u32 value at address `0x10`, increment it, and store the = updated value back: + /// + /// ```no_run + /// use kernel::io::{ + /// Io, + /// Mmio, + /// }; + /// + /// fn do_update(io: &Mmio<0x1000>) { + /// io.update(0x10, |v: u32| { + /// v + 1 + /// }) + /// } + /// ``` #[inline(always)] fn update(&self, location: L, f: F) where --=20 2.53.0 From nobody Thu Apr 2 20:26:43 2026 Received: from DM1PR04CU001.outbound.protection.outlook.com (mail-centralusazon11010006.outbound.protection.outlook.com [52.101.61.6]) (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 C3EF723183F; Sat, 14 Mar 2026 01:07:03 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.61.6 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450426; cv=fail; b=j3jleQah5eO44DztQkXTQxCeD/nFkXgSPuqNy2/DQ7lRXn5/qR32fdCM6Edr/PnximhxivxzykyIsjBcfy9ueqh8idYh678yASYUh5DCL+exIzrEHg2ledWM1aFgbY8ertJn4KxGlrcZ5AyxH21YDobrnBg7P5F2YxA9ZrpVBa8= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450426; c=relaxed/simple; bh=7nwpqxDuy/0GCDVhx5XjZqmmTMSZ8Tn5EQ0NLp68obI=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=W8U3ydxNvvwc2l4s4c1V1+GpkIFctFpYFyTgU36k+FA34OtdYHX8A9EIdDheSbFrNc73plEQljSHkbGYtOY4evdiTGXuavEGdi58B9PXyvnFl6kBLOXAsxtRtDaucf3OGpv37mxAVMnawmFD0GY2dRLApO5jMID9m/KSoEtOTKU= 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=JxKXXAoF; arc=fail smtp.client-ip=52.101.61.6 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="JxKXXAoF" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=fLV93x/iThIHkzvdhNflyxy8EXwd+zwF+fgejSke634wpBgcyLHKr3zfYt1nFfAFmEzaX+a7/NZEbzyTIHaT5lMFNnRo920RoAiioIZkZaLmvBicGGLgMSYsVawmrRvJisT7kReOqh66VzM53kxdX/BcWSv4bSGsmY8Hrbp2f6UEBHK54utY19mJWoit5frdMC15WHRvDB8EVOPuqevkcrs0+E5xgaX6dROnMdPg+gdSid4j8YhveDBu+EMNKcf7TeAKrI+IrOD7MgmBLpwZMRXq6mdQoRPo7YJXgAdO7BPNfwKjbqLqD2EuFeJ8tuD+SH8WsKZrz81ftHHt2SEDAg== 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=gRwuX5g9k/PYDv+6hs3Iy3jGlN9yzSelg48Vgq1DJgg=; b=Vuqe+SY6D+iaXLI22TY6gNgsKjvsuPC+WjBYvB3S8cG+nLEYmXZ9KISg3vib41sFRPUXGyTw0hnsBYZvKFUTCWE9UFCOaS32nMBeKAIBKiv0gwD8c1nDnuMciw3DvuG9yH3y/eyzNoyNrOQ9kaPMnOIbZSFnQ7fELHEJ3rY7cuZFq9Yhm+RNLl5Dd30mF9S/MCqX68ZnzBg9PNdL3CgkbFbCju7N2q9gpVPSOWPxoGMukSYcqBNPYUbv/0zbPPL4lZ3F97KWpn91b1anNS1++ZbfMUAdwZ8SLU50eXWtMliOphYYXArFPeZzJF7pi0I0hBI9Tisvk8YrWuSAnn9Wzg== 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=gRwuX5g9k/PYDv+6hs3Iy3jGlN9yzSelg48Vgq1DJgg=; b=JxKXXAoFmlBAZnpKTFf+x+1JKj99KN+N7pTPXH3z43DgSQ54mt7Uu/oSA4dOzxM0ip6MEkDY24IHLrBVyhxz4EvzD2JJdqJSzqGP6RNFDshnys6fcCnvJZjMwpnz2rqeaVOiWHpWv8UVZFR1+HjIF0XZaiuDVlGI0UwEZi2RwxUDYbHIQcAsrrqLeHOsabCVlrHt80W9qf8wglTizrfSEt5SGt1L2EApvFSgFOpYHItcdH1iTPjXuNf9smmmsHzsQA+O1rLzXpqiLgB9SsUpFJf+q6YJOSm8MTUG7rmqDZSG16TVQpIRgA/i2W7wXpp3h7TqcEwZOX2PRg/Jbk8JRQ== 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 BY5PR12MB4033.namprd12.prod.outlook.com (2603:10b6:a03:213::22) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9723.6; Sat, 14 Mar 2026 01:06:55 +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.9723.000; Sat, 14 Mar 2026 01:06:55 +0000 From: Alexandre Courbot Date: Sat, 14 Mar 2026 10:06:17 +0900 Subject: [PATCH v9 07/10] rust: io: add `register!` macro Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260314-register-v9-7-86805b2f7e9d@nvidia.com> References: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> In-Reply-To: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> To: Danilo Krummrich , Alice Ryhl , Daniel Almeida , Miguel Ojeda , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Boqun Feng Cc: Yury Norov , John Hubbard , Alistair Popple , Joel Fernandes , Timur Tabi , Edwin Peer , Eliot Courtney , Dirk Behme , Steven Price , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alexandre Courbot X-Mailer: b4 0.14.3 X-ClientProxiedBy: TY4PR01CA0057.jpnprd01.prod.outlook.com (2603:1096:405:372::9) 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_|BY5PR12MB4033:EE_ X-MS-Office365-Filtering-Correlation-Id: c0088197-502c-472f-8d0a-08de8165fbae X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|376014|7416014|10070799003|921020|22082099003|56012099003|18002099003; X-Microsoft-Antispam-Message-Info: B0t6FyrXoZlZ6hrK8X/xWfNtKDxBTA0itB+eY22eF75+C9UrFt47DcPnVPb//rKptJwFUKL9S/Oxk11K0Wsr3MLl2QosO576GLC46S+/jkscaP9ybow7La12XlNHCyKO/71XTi6Zud6sKonTbGDfZ7imEp3RgwVIAM13ROlC1KUPc+uA+qJzQuC55r+VRRW0QmA0a69vdJftED7MzkxrkatkywTa5+en2jj8n96idw6TYTMePgzZ1E4LAA4yKpaJ5P31iwHobkPsehAeAZx3ztztcfoHQRrh1GdU+WhJ01tqNsZG03aKwr5kHDQw+DLTvzffQ+W21fsENZ0/4rlHuE8B+CWwi4JpXLEYMbWP3AL3HR+YGb//PPub6fRq0/vWZCrXy3r1r4xrTTkYT8HkjqT5B9UnP13lS4dI7scf8u+uc2iveC8AM6KZTSsP8I9FB8ZnmYeUDGP3x4EpnFdNOMGEKzW6q8iw8IP5f7knBBx0i8jYJdUgjveXoY5vqKW25nFjBla4SAE8yooNeeherk5KcNIlSClLRmPD1Xo2I+PhdPWxQm8NhZgJKKnzUSoLyNskqc/wLOzk6i7h2HY8nt0IXc0ETjHSixoxCxT0ejdtZzoAKG178DImKmYgs4t2cjnp6MIuH4/2K5ALMbgaiFALJ6N9ISMLAObsO130pxWIi5Ld0UfG85Z2Xi4xPbVGRtQadMqagMje8RRSZpND+L1qcP1rbgTvNIAdSfpvqils/JVuyj16X5iPMC8bmXzUEHDUaumR88rOfVu/S3gp7ZbQatJ2mpxU56a6/f9006A= 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)(366016)(1800799024)(376014)(7416014)(10070799003)(921020)(22082099003)(56012099003)(18002099003);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 2 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?U25JMHJyVVEzV2tJMk9GMnBOMzNUOG5jWEdZd3BiNTBqWnozZitSOW0wcC9G?= =?utf-8?B?RDVOYUNqL2lRSkRLRTBzcXU2QkM1NGdkRzZUN0FocnZuUVZWRFVNc1B3WDhL?= =?utf-8?B?ZHVEUnltTi9CeTVwVS9CclM1Y25yeE8wd3R6b2hVOEM1WmxodC93QXRZczdS?= =?utf-8?B?RmROOGdYMEtJRlV0Z0R1Y0d5U2oxU3RwSkRKM3VMWEZMN0NjeEt6UW8rQmg3?= =?utf-8?B?VDlCOEw1TkQreTViaEFMZ3pKbnd1eGI5U3ZTL0cvS3VYWldDOVFmbHhjS3N4?= =?utf-8?B?Q1prRzZCUHNYRDliYTc4UCt1dk5JY2VtOVlqT1JaTnI0NHE1VE5HRlV2RzF0?= =?utf-8?B?K2xGM3VuSnpTWHRFbVdvZFB6ZkxpeGV2TmJ6SG1Xdlo3SkxodjBUNXUyUDR1?= =?utf-8?B?dWRiVllucFQ5ek5NMWtob09Wd0FBLzdCYllaT09HNW9MdGcrMjU2NjhoRTRE?= =?utf-8?B?cmJNeEI2SFlsRHZab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?B?MWZ2cVJpdnVWOU1YUUp1czB0cFA5cVd5MThReW9aOVMxMERaMVlzS3dnTWFs?= =?utf-8?Q?wgM266O99Qls93wOxtHcqV3K4ELx0BQfDc8ZhLROXbObN?= X-MS-Exchange-AntiSpam-MessageData-1: YvOefn8DWW56lQ== X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: c0088197-502c-472f-8d0a-08de8165fbae X-MS-Exchange-CrossTenant-AuthSource: CH2PR12MB3990.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 14 Mar 2026 01:06:55.0972 (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: DjCwPFOCuaDm7qUy4b3DAKn9QbKtg17BMVFMn5MD+VNB+EARFEs+UDSWb0w+jslh0rVDgX0bejjeaXyRK4PeJA== X-MS-Exchange-Transport-CrossTenantHeadersStamped: BY5PR12MB4033 Add a macro for defining hardware register types with I/O accessors. Each register field is represented as a `Bounded` of the appropriate bit width, ensuring field values are never silently truncated. Fields can optionally be converted to/from custom types, either fallibly or infallibly. The address of registers can be direct, relative, or indexed, supporting most of the patterns in which registers are arranged. Suggested-by: Danilo Krummrich Link: https://lore.kernel.org/all/20250306222336.23482-6-dakr@kernel.org/ Co-developed-by: Gary Guo Signed-off-by: Gary Guo Signed-off-by: Alexandre Courbot --- rust/kernel/io.rs | 5 +- rust/kernel/io/register.rs | 1227 ++++++++++++++++++++++++++++++++++++++++= ++++ 2 files changed, 1231 insertions(+), 1 deletion(-) diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index c9d43b1372ab..bfea30a9acdf 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -11,8 +11,10 @@ =20 pub mod mem; pub mod poll; +pub mod register; pub mod resource; =20 +pub use crate::register; pub use resource::Resource; =20 /// Physical address type. @@ -179,7 +181,8 @@ pub trait IoCapable { /// This trait is the key abstraction allowing [`Io::read`], [`Io::write`]= , and [`Io::update`] (and /// their fallible [`try_read`](Io::try_read), [`try_write`](Io::try_write= ) and /// [`try_update`](Io::try_update) counterparts) to work uniformly with bo= th raw [`usize`] offsets -/// (for primitive types like [`u32`]) and typed ones. +/// (for primitive types like [`u32`]) and typed ones (like those generate= d by the [`register!`] +/// macro). /// /// An `IoLoc` carries three pieces of information: /// diff --git a/rust/kernel/io/register.rs b/rust/kernel/io/register.rs new file mode 100644 index 000000000000..40085953c831 --- /dev/null +++ b/rust/kernel/io/register.rs @@ -0,0 +1,1227 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Macro to define register layout and accessors. +//! +//! The [`register!`](kernel::io::register!) macro provides an intuitive a= nd readable syntax for +//! defining a dedicated type for each register and accessing it using [`I= o`](super::Io). Each such +//! type comes with its own field accessors that can return an error if a = field's value is invalid. +//! +//! Note: most of the items in this module are public so they can be refer= enced by the macro, but +//! most are not to be used directly by users. Outside of the `register!` = macro itself, the only +//! items you might want to import from this module are [`WithBase`] and [= `Array`]. +//! +//! # Simple example +//! +//! ```no_run +//! use kernel::io::register; +//! +//! register! { +//! /// Basic information about the chip. +//! pub BOOT_0(u32) @ 0x00000100 { +//! /// Vendor ID. +//! 15:8 vendor_id; +//! /// Major revision of the chip. +//! 7:4 major_revision; +//! /// Minor revision of the chip. +//! 3:0 minor_revision; +//! } +//! } +//! ``` +//! +//! This defines a 32-bit `BOOT_0` type which can be read from or written = to offset `0x100` of an +//! `Io` region, with the described bitfields. For instance, `minor_revisi= on` consists of the 4 +//! least significant bits of the type. +//! +//! Fields are instances of [`Bounded`](kernel::num::Bounded) and can be r= ead by calling their +//! getter method, which is named after them. They also have setter method= s prefixed with `with_` +//! for runtime values and `with_const_` for constant values. All setters = return the updated +//! register value. +//! +//! Fields can also be transparently converted from/to an arbitrary type b= y using the `=3D>` and +//! `?=3D>` syntaxes. +//! +//! If present, doc comments above register or fields definitions are adde= d to the relevant item +//! they document (the register type itself, or the field's setter and get= ter methods). +//! +//! Note that multiple registers can be defined in a single `register!` in= vocation. This can be +//! useful to group related registers together. +//! +//! Here is how the register defined above can be used in code: +//! +//! +//! ```no_run +//! use kernel::{ +//! io::{ +//! register, +//! Io, +//! IoLoc, +//! }, +//! num::Bounded, +//! }; +//! # use kernel::io::Mmio; +//! # register! { +//! # pub BOOT_0(u32) @ 0x00000100 { +//! # 15:8 vendor_id; +//! # 7:4 major_revision; +//! # 3:0 minor_revision; +//! # } +//! # } +//! # fn test(io: &Mmio<0x1000>) { +//! # fn obtain_vendor_id() -> u8 { 0xff } +//! +//! // Read from the register's defined offset (0x100). +//! let boot0 =3D io.read(BOOT_0); +//! pr_info!("chip revision: {}.{}", boot0.major_revision().get(), boot0.m= inor_revision().get()); +//! +//! // Update some fields and write the new value back. +//! let new_boot0 =3D boot0 +//! // Constant values. +//! .with_const_major_revision::<3>() +//! .with_const_minor_revision::<10>() +//! // Run-time value. +//! .with_vendor_id(obtain_vendor_id()); +//! io.write((), new_boot0); +//! +//! // Or, build a new value from zero and write it: +//! io.write((), BOOT_0::zeroed() +//! .with_const_major_revision::<3>() +//! .with_const_minor_revision::<10>() +//! .with_vendor_id(obtain_vendor_id()) +//! ); +//! +//! // Or, read and update the register in a single step. +//! io.update(BOOT_0, |r| r +//! .with_const_major_revision::<3>() +//! .with_const_minor_revision::<10>() +//! .with_vendor_id(obtain_vendor_id()) +//! ); +//! +//! // Constant values can also be built using the const setters. +//! const V: BOOT_0 =3D pin_init::zeroed::() +//! .with_const_major_revision::<3>() +//! .with_const_minor_revision::<10>(); +//! # } +//! ``` +//! +//! For more extensive documentation about how to define registers, see the +//! [`register!`](kernel::io::register!) macro. + +use core::marker::PhantomData; + +use crate::io::IoLoc; + +/// Trait implemented by all registers. +pub trait Register: Sized { + /// Backing primitive type of the register. + type Storage: Into + From; + + /// Start offset of the register. + /// + /// The interpretation of this offset depends on the type of the regis= ter. + const OFFSET: usize; +} + +/// Trait implemented by registers with a fixed offset. +pub trait FixedRegister: Register {} + +/// Allows `()` to be used as the `location` parameter of [`Io::write`](su= per::Io::write) when +/// passing a [`FixedRegister`] value. +impl IoLoc for () +where + T: FixedRegister, +{ + type IoType =3D T::Storage; + + #[inline(always)] + fn offset(self) -> usize { + T::OFFSET + } +} + +/// A [`FixedRegister`] carries its location in its type. Thus `FixedRegis= ter` values can be used +/// as an [`IoLoc`]. +impl IoLoc for T +where + T: FixedRegister, +{ + type IoType =3D T::Storage; + + #[inline(always)] + fn offset(self) -> usize { + T::OFFSET + } +} + +/// Location of a fixed register. +pub struct FixedRegisterLoc(PhantomData); + +impl FixedRegisterLoc { + /// Returns the location of `T`. + #[inline(always)] + // We do not implement `Default` so we can be const. + #[allow(clippy::new_without_default)] + pub const fn new() -> Self { + Self(PhantomData) + } +} + +impl IoLoc for FixedRegisterLoc +where + T: FixedRegister, +{ + type IoType =3D T::Storage; + + #[inline(always)] + fn offset(self) -> usize { + T::OFFSET + } +} + +/// Trait providing a base address to be added to the offset of a relative= register to obtain +/// its actual offset. +/// +/// The `T` generic argument is used to distinguish which base to use, in = case a type provides +/// several bases. It is given to the `register!` macro to restrict the us= e of the register to +/// implementors of this particular variant. +pub trait RegisterBase { + /// Base address to which register offsets are added. + const BASE: usize; +} + +/// Trait implemented by all registers that are relative to a base. +pub trait WithBase { + /// Family of bases applicable to this register. + type BaseFamily; + + /// Returns the absolute location of this type when using `B` as its b= ase. + #[inline(always)] + fn of>() -> RelativeRegisterLoc + where + Self: Register, + { + RelativeRegisterLoc::new() + } +} + +/// Trait implemented by relative registers. +pub trait RelativeRegister: Register + WithBase {} + +/// Location of a relative register. +/// +/// This can either be an immediately accessible regular [`RelativeRegiste= r`], or a +/// [`RelativeRegisterArray`] that needs one additional resolution through +/// [`RelativeRegisterLoc::at`]. +pub struct RelativeRegisterLoc(PhantomData, Pha= ntomData); + +impl RelativeRegisterLoc +where + T: Register + WithBase, + B: RegisterBase + ?Sized, +{ + /// Returns the location of a relative register or register array. + #[inline(always)] + // We do not implement `Default` so we can be const. + #[allow(clippy::new_without_default)] + pub const fn new() -> Self { + Self(PhantomData, PhantomData) + } + + // Returns the absolute offset of the relative register using base `B`. + // + // This is implemented as a private const method so it can be reused b= y the [`IoLoc`] + // implementations of both [`RelativeRegisterLoc`] and [`RelativeRegis= terArrayLoc`]. + const fn offset(self) -> usize { + B::BASE + T::OFFSET + } +} + +impl IoLoc for RelativeRegisterLoc +where + T: RelativeRegister, + B: RegisterBase + ?Sized, +{ + type IoType =3D T::Storage; + + #[inline(always)] + fn offset(self) -> usize { + RelativeRegisterLoc::offset(self) + } +} + +/// Trait implemented by arrays of registers. +pub trait RegisterArray: Register { + /// Number of elements in the registers array. + const SIZE: usize; + /// Number of bytes between the start of elements in the registers arr= ay. + const STRIDE: usize; +} + +/// Location of an array register. +pub struct RegisterArrayLoc(usize, PhantomData); + +impl RegisterArrayLoc { + /// Returns the location of register `T` at position `idx`, with build= -time validation. + #[inline(always)] + pub fn new(idx: usize) -> Self { + ::kernel::build_assert!(idx < T::SIZE); + + Self(idx, PhantomData) + } + + /// Attempts to return the location of register `T` at position `idx`,= with runtime validation. + #[inline(always)] + pub fn try_new(idx: usize) -> Option { + if idx < T::SIZE { + Some(Self(idx, PhantomData)) + } else { + None + } + } +} + +impl IoLoc for RegisterArrayLoc +where + T: RegisterArray, +{ + type IoType =3D T::Storage; + + #[inline(always)] + fn offset(self) -> usize { + T::OFFSET + self.0 * T::STRIDE + } +} + +/// Trait providing location builders for [`RegisterArray`]s. +pub trait Array { + /// Returns the location of the register at position `idx`, with build= -time validation. + #[inline(always)] + fn at(idx: usize) -> RegisterArrayLoc + where + Self: RegisterArray, + { + RegisterArrayLoc::new(idx) + } + + /// Returns the location of the register at position `idx`, with runti= me validation. + #[inline(always)] + fn try_at(idx: usize) -> Option> + where + Self: RegisterArray, + { + RegisterArrayLoc::try_new(idx) + } +} + +/// Trait implemented by arrays of relative registers. +pub trait RelativeRegisterArray: RegisterArray + WithBase {} + +/// Location to a relative array register. +pub struct RelativeRegisterArrayLoc< + T: RelativeRegisterArray, + B: RegisterBase + ?Sized, +>(RelativeRegisterLoc, usize); + +impl RelativeRegisterArrayLoc +where + T: RelativeRegisterArray, + B: RegisterBase + ?Sized, +{ + /// Returns the location of register `T` from the base `B` at index `i= dx`, with build-time + /// validation. + #[inline(always)] + pub fn new(idx: usize) -> Self { + ::kernel::build_assert!(idx < T::SIZE); + + Self(RelativeRegisterLoc::new(), idx) + } + + /// Attempts to return the location of register `T` from the base `B` = at index `idx`, with + /// runtime validation. + #[inline(always)] + pub fn try_new(idx: usize) -> Option { + if idx < T::SIZE { + Some(Self(RelativeRegisterLoc::new(), idx)) + } else { + None + } + } +} + +/// Methods exclusive to [`RelativeRegisterLoc`]s created with a [`Relativ= eRegisterArray`]. +impl RelativeRegisterLoc +where + T: RelativeRegisterArray, + B: RegisterBase + ?Sized, +{ + /// Returns the location of the register at position `idx`, with build= -time validation. + #[inline(always)] + pub fn at(self, idx: usize) -> RelativeRegisterArrayLoc { + RelativeRegisterArrayLoc::new(idx) + } + + /// Returns the location of the register at position `idx`, with runti= me validation. + #[inline(always)] + pub fn try_at(self, idx: usize) -> Option> { + RelativeRegisterArrayLoc::try_new(idx) + } +} + +impl IoLoc for RelativeRegisterArrayLoc +where + T: RelativeRegisterArray, + B: RegisterBase + ?Sized, +{ + type IoType =3D T::Storage; + + #[inline(always)] + fn offset(self) -> usize { + self.0.offset() + self.1 * T::STRIDE + } +} + +/// Defines a dedicated type for a register, including getter and setter m= ethods for its fields and +/// methods to read and write it from an [`Io`](kernel::io::Io) region. +/// +/// This documentation focuses on how to declare registers. See the [modul= e-level +/// documentation](mod@kernel::io::register) for examples of how to access= them. +/// +/// There are 4 possible kinds of registers: fixed offset registers, relat= ive registers, arrays of +/// registers, and relative arrays of registers. +/// +/// ## Fixed offset registers +/// +/// These are the simplest kind of registers. Their location is simply an = offset inside the I/O +/// region. For instance: +/// +/// ```ignore +/// register! { +/// pub FIXED_REG(u16) @ 0x80 { +/// ... +/// } +/// } +/// ``` +/// +/// This creates a 16-bit register named `FIXED_REG` located at offset `0x= 80` of an I/O region. +/// +/// These registers' location can be built simply by referencing their nam= e: +/// +/// ```no_run +/// use kernel::{ +/// io::{ +/// register, +/// Io, +/// }, +/// }; +/// # use kernel::io::Mmio; +/// +/// register! { +/// FIXED_REG(u32) @ 0x100 { +/// 16:8 high_byte; +/// 7:0 low_byte; +/// } +/// } +/// +/// # fn test(io: &Mmio<0x1000>) { +/// let val =3D io.read(FIXED_REG); +/// +/// // Write from an already-existing value. +/// io.write(FIXED_REG, val.with_low_byte(0xff)); +/// +/// // Create a register value from scratch. +/// let val2 =3D FIXED_REG::zeroed().with_high_byte(0x80); +/// +/// // The location of fixed offset registers is already contained in thei= r type. Thus, the +/// // `location` argument of `Io::write` is technically redundant and can= be replaced by `()`. +/// io.write((), val2); +/// # } +/// +/// ``` +/// +/// It is possible to create an alias of an existing register with new fie= ld definitions by using +/// the `=3D> ALIAS` syntax. This is useful for cases where a register's i= nterpretation depends on +/// the context: +/// +/// ```no_run +/// use kernel::io::register; +/// +/// register! { +/// /// Scratch register. +/// pub SCRATCH(u32) @ 0x00000200 { +/// 31:0 value; +/// } +/// +/// /// Boot status of the firmware. +/// pub SCRATCH_BOOT_STATUS(u32) =3D> SCRATCH { +/// 0:0 completed; +/// } +/// } +/// ``` +/// +/// In this example, `SCRATCH_BOOT_STATUS` uses the same I/O address as `S= CRATCH`, while providing +/// its own `completed` field. +/// +/// ## Relative registers +/// +/// Relative registers can be instantiated several times at a relative off= set of a group of bases. +/// For instance, imagine the following I/O space: +/// +/// ```text +/// +-----------------------------+ +/// | ... | +/// | | +/// 0x100--->+------------CPU0-------------+ +/// | | +/// 0x110--->+-----------------------------+ +/// | CPU_CTL | +/// +-----------------------------+ +/// | ... | +/// | | +/// | | +/// 0x200--->+------------CPU1-------------+ +/// | | +/// 0x210--->+-----------------------------+ +/// | CPU_CTL | +/// +-----------------------------+ +/// | ... | +/// +-----------------------------+ +/// ``` +/// +/// `CPU0` and `CPU1` both have a `CPU_CTL` register that starts at offset= `0x10` of their I/O +/// space segment. Since both instances of `CPU_CTL` share the same layout= , we don't want to define +/// them twice and would prefer a way to select which one to use from a si= ngle definition. +/// +/// This can be done using the `Base + Offset` syntax when specifying the = register's address: +/// +/// ```ignore +/// register! { +/// pub RELATIVE_REG(u32) @ Base + 0x80 { +/// ... +/// } +/// } +/// ``` +/// +/// This creates a register with an offset of `0x80` from a given base. +/// +/// `Base` is an arbitrary type (typically a ZST) to be used as a generic = parameter of the +/// [`RegisterBase`] trait to provide the base as a constant, i.e. each ty= pe providing a base for +/// this register needs to implement `RegisterBase`. +/// +/// The location of relative registers can be built using the [`WithBase::= of`] method to specify +/// its base. All relative registers implement [`WithBase`]. +/// +/// Here is the above layout translated into code: +/// +/// ```no_run +/// use kernel::{ +/// io::{ +/// register, +/// register::{ +/// RegisterBase, +/// WithBase, +/// }, +/// Io, +/// }, +/// }; +/// # use kernel::io::Mmio; +/// +/// // Type used to identify the base. +/// pub struct CpuCtlBase; +/// +/// // ZST describing `CPU0`. +/// struct Cpu0; +/// impl RegisterBase for Cpu0 { +/// const BASE: usize =3D 0x100; +/// } +/// +/// // ZST describing `CPU1`. +/// struct Cpu1; +/// impl RegisterBase for Cpu1 { +/// const BASE: usize =3D 0x200; +/// } +/// +/// // This makes `CPU_CTL` accessible from all implementors of `RegisterB= ase`. +/// register! { +/// /// CPU core control. +/// pub CPU_CTL(u32) @ CpuCtlBase + 0x10 { +/// 0:0 start; +/// } +/// } +/// +/// # fn test(io: Mmio<0x1000>) { +/// // Read the status of `Cpu0`. +/// let cpu0_started =3D io.read(CPU_CTL::of::()); +/// +/// // Stop `Cpu0`. +/// io.write(WithBase::of::(), CPU_CTL::zeroed()); +/// # } +/// +/// // Aliases can also be defined for relative register. +/// register! { +/// /// Alias to CPU core control. +/// pub CPU_CTL_ALIAS(u32) =3D> CpuCtlBase + CPU_CTL { +/// /// Start the aliased CPU core. +/// 1:1 alias_start; +/// } +/// } +/// +/// # fn test2(io: Mmio<0x1000>) { +/// // Start the aliased `CPU0`, leaving its other fields untouched. +/// io.update(CPU_CTL_ALIAS::of::(), |r| r.with_alias_start(true)); +/// # } +/// ``` +/// +/// ## Arrays of registers +/// +/// Some I/O areas contain consecutive registers that share the same field= layout. These areas can +/// be defined as an array of identical registers, allowing them to be acc= essed by index with +/// compile-time or runtime bound checking: +/// +/// +/// ```ignore +/// register! { +/// pub REGISTER_ARRAY(u8)[10, stride =3D 4] @ 0x100 { +/// ... +/// } +/// } +/// ``` +/// +/// This defines `REGISTER_ARRAY`, an array of 10 byte registers starting = at offset `0x100`. Each +/// register is separated from its neighbor by 4 bytes. +/// +/// The `stride` parameter is optional; if unspecified, the registers are = placed consecutively from +/// each other. +/// +/// A location for a register in a register array is built using the [`Arr= ay::at`] trait method. +/// All arrays of registers implement [`Array`]. +/// +/// ```no_run +/// use kernel::{ +/// io::{ +/// register, +/// register::Array, +/// Io, +/// }, +/// }; +/// # use kernel::io::Mmio; +/// # fn get_scratch_idx() -> usize { +/// # 0x15 +/// # } +/// +/// // Array of 64 consecutive registers with the same layout starting at = offset `0x80`. +/// register! { +/// /// Scratch registers. +/// pub SCRATCH(u32)[64] @ 0x00000080 { +/// 31:0 value; +/// } +/// } +/// +/// # fn test(io: &Mmio<0x1000>) +/// # -> Result<(), Error>{ +/// // Read scratch register 0, i.e. I/O address `0x80`. +/// let scratch_0 =3D io.read(SCRATCH::at(0)).value(); +/// +/// // Write scratch register 15, i.e. I/O address `0x80 + (15 * 4)`. +/// io.write(Array::at(15), SCRATCH::from(0xffeeaabb)); +/// +/// // This is out of bounds and won't build. +/// // let scratch_128 =3D io.read(SCRATCH::at(128)).value(); +/// +/// // Runtime-obtained array index. +/// let idx =3D get_scratch_idx(); +/// // Access on a runtime index returns an error if it is out-of-bounds. +/// let some_scratch =3D io.read(SCRATCH::try_at(idx).ok_or(EINVAL)?).valu= e(); +/// +/// // Alias to a specific register in an array. +/// // Here `SCRATCH[8]` is used to convey the firmware exit code. +/// register! { +/// /// Firmware exit status code. +/// pub FIRMWARE_STATUS(u32) =3D> SCRATCH[8] { +/// 7:0 status; +/// } +/// } +/// +/// let status =3D io.read(FIRMWARE_STATUS).status(); +/// +/// // Non-contiguous register arrays can be defined by adding a stride pa= rameter. +/// // Here, each of the 16 registers of the array are separated by 8 byte= s, meaning that the +/// // registers of the two declarations below are interleaved. +/// register! { +/// /// Scratch registers bank 0. +/// pub SCRATCH_INTERLEAVED_0(u32)[16, stride =3D 8] @ 0x000000c0 { +/// 31:0 value; +/// } +/// +/// /// Scratch registers bank 1. +/// pub SCRATCH_INTERLEAVED_1(u32)[16, stride =3D 8] @ 0x000000c4 { +/// 31:0 value; +/// } +/// } +/// # Ok(()) +/// # } +/// ``` +/// +/// ## Relative arrays of registers +/// +/// Combining the two features described in the sections above, arrays of = registers accessible from +/// a base can also be defined: +/// +/// ```ignore +/// register! { +/// pub RELATIVE_REGISTER_ARRAY(u8)[10, stride =3D 4] @ Base + 0x100 { +/// ... +/// } +/// } +/// ``` +/// +/// Like relative registers, they implement the [`WithBase`] trait. Howeve= r the return value of +/// [`WithBase::of`] cannot be used directly as a location and must be fur= ther specified using the +/// [`at`](RelativeRegisterLoc::at) method. +/// +/// ```no_run +/// use kernel::{ +/// io::{ +/// register, +/// register::{ +/// RegisterBase, +/// WithBase, +/// }, +/// Io, +/// }, +/// }; +/// # use kernel::io::Mmio; +/// # fn get_scratch_idx() -> usize { +/// # 0x15 +/// # } +/// +/// // Type used as parameter of `RegisterBase` to specify the base. +/// pub struct CpuCtlBase; +/// +/// // ZST describing `CPU0`. +/// struct Cpu0; +/// impl RegisterBase for Cpu0 { +/// const BASE: usize =3D 0x100; +/// } +/// +/// // ZST describing `CPU1`. +/// struct Cpu1; +/// impl RegisterBase for Cpu1 { +/// const BASE: usize =3D 0x200; +/// } +/// +/// // 64 per-cpu scratch registers, arranged as a contiguous array. +/// register! { +/// /// Per-CPU scratch registers. +/// pub CPU_SCRATCH(u32)[64] @ CpuCtlBase + 0x00000080 { +/// 31:0 value; +/// } +/// } +/// +/// # fn test(io: &Mmio<0x1000>) -> Result<(), Error> { +/// // Read scratch register 0 of CPU0. +/// let scratch =3D io.read(CPU_SCRATCH::of::().at(0)); +/// +/// // Write the retrieved value into scratch register 15 of CPU1. +/// io.write(WithBase::of::().at(15), scratch); +/// +/// // This won't build. +/// // let cpu0_scratch_128 =3D io.read(CPU_SCRATCH::of::().at(128))= .value(); +/// +/// // Runtime-obtained array index. +/// let scratch_idx =3D get_scratch_idx(); +/// // Access on a runtime index returns an error if it is out-of-bounds. +/// let cpu0_scratch =3D io.read( +/// CPU_SCRATCH::of::().try_at(scratch_idx).ok_or(EINVAL)? +/// ).value(); +/// # Ok(()) +/// # } +/// +/// // Alias to `SCRATCH[8]` used to convey the firmware exit code. +/// register! { +/// /// Per-CPU firmware exit status code. +/// pub CPU_FIRMWARE_STATUS(u32) =3D> CpuCtlBase + CPU_SCRATCH[8] { +/// 7:0 status; +/// } +/// } +/// +/// // Non-contiguous relative register arrays can be defined by adding a = stride parameter. +/// // Here, each of the 16 registers of the array are separated by 8 byte= s, meaning that the +/// // registers of the two declarations below are interleaved. +/// register! { +/// /// Scratch registers bank 0. +/// pub CPU_SCRATCH_INTERLEAVED_0(u32)[16, stride =3D 8] @ CpuCtlBase = + 0x00000d00 { +/// 31:0 value; +/// } +/// +/// /// Scratch registers bank 1. +/// pub CPU_SCRATCH_INTERLEAVED_1(u32)[16, stride =3D 8] @ CpuCtlBase = + 0x00000d04 { +/// 31:0 value; +/// } +/// } +/// +/// # fn test2(io: &Mmio<0x1000>) -> Result<(), Error> { +/// let cpu0_status =3D io.read(CPU_FIRMWARE_STATUS::of::()).status(= ); +/// # Ok(()) +/// # } +/// ``` +#[macro_export] +macro_rules! register { + // Entry point for the macro, allowing multiple registers to be define= d in one call. + // It matches all possible register declaration patterns to dispatch t= hem to corresponding + // `@reg` rule that defines a single register. + ( + $( + $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) + $([ $size:expr $(, stride =3D $stride:expr)? ])? + $(@ $($base:ident +)? $offset:literal)? + $(=3D> $alias:ident $(+ $alias_offset:ident)? $([$alias_id= x:expr])? )? + { $($fields:tt)* } + )* + ) =3D> { + $( + $crate::register!( + @reg $(#[$attr])* $vis $name ($storage) $([$size $(, stride = =3D $stride)?])? + $(@ $($base +)? $offset)? + $(=3D> $alias $(+ $alias_offset)? $([$alias_idx])? )? + { $($fields)* } + ); + )* + }; + + // All the rules below are private helpers. + + // Creates a register at a fixed offset of the MMIO space. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) @ $offse= t:literal + { $($fields:tt)* } + ) =3D> { + $crate::register!(@bitfield $(#[$attr])* $vis struct $name($storag= e) { $($fields)* }); + $crate::register!(@io_base $name($storage) @ $offset); + $crate::register!(@io_fixed $(#[$attr])* $vis $name($storage)); + }; + + // Creates an alias register of fixed offset register `alias` with its= own fields. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) =3D> $al= ias:ident + { $($fields:tt)* } + ) =3D> { + $crate::register!(@bitfield $(#[$attr])* $vis struct $name($storag= e) { $($fields)* }); + $crate::register!( + @io_base $name($storage) @ + <$alias as $crate::io::register::Register>::OFFSET + ); + $crate::register!(@io_fixed $(#[$attr])* $vis $name($storage)); + }; + + // Creates a register at a relative offset from a base address provide= r. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) @ $base:= ident + $offset:literal + { $($fields:tt)* } + ) =3D> { + $crate::register!(@bitfield $(#[$attr])* $vis struct $name($storag= e) { $($fields)* }); + $crate::register!(@io_base $name($storage) @ $offset); + $crate::register!(@io_relative $vis $name($storage) @ $base); + }; + + // Creates an alias register of relative offset register `alias` with = its own fields. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) =3D> $ba= se:ident + $alias:ident + { $($fields:tt)* } + ) =3D> { + $crate::register!(@bitfield $(#[$attr])* $vis struct $name($storag= e) { $($fields)* }); + $crate::register!( + @io_base $name($storage) @ <$alias as $crate::io::register::Re= gister>::OFFSET + ); + $crate::register!(@io_relative $vis $name($storage) @ $base); + }; + + // Creates an array of registers at a fixed offset of the MMIO space. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) + [ $size:expr, stride =3D $stride:expr ] @ $offset:literal { $(= $fields:tt)* } + ) =3D> { + static_assert!(::core::mem::size_of::<$storage>() <=3D $stride); + + $crate::register!(@bitfield $(#[$attr])* $vis struct $name($storag= e) { $($fields)* }); + $crate::register!(@io_base $name($storage) @ $offset); + $crate::register!(@io_array $vis $name($storage) [ $size, stride = =3D $stride ]); + }; + + // Shortcut for contiguous array of registers (stride =3D=3D size of e= lement). + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) [ $size:= expr ] @ $offset:literal + { $($fields:tt)* } + ) =3D> { + $crate::register!( + $(#[$attr])* $vis $name($storage) [ $size, stride =3D ::core::= mem::size_of::<$storage>() ] + @ $offset { $($fields)* } + ); + }; + + // Creates an alias of register `idx` of array of registers `alias` wi= th its own fields. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) =3D> $al= ias:ident [ $idx:expr ] + { $($fields:tt)* } + ) =3D> { + static_assert!($idx < <$alias as $crate::io::register::RegisterArr= ay>::SIZE); + + $crate::register!(@bitfield $(#[$attr])* $vis struct $name($storag= e) { $($fields)* }); + $crate::register!( + @io_base $name($storage) @ + <$alias as $crate::io::register::Register>::OFFSET + + $idx * <$alias as $crate::io::register::RegisterArray>::= STRIDE + ); + $crate::register!(@io_fixed $(#[$attr])* $vis $name($storage)); + }; + + // Creates an array of registers at a relative offset from a base addr= ess provider. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) + [ $size:expr, stride =3D $stride:expr ] + @ $base:ident + $offset:literal { $($fields:tt)* } + ) =3D> { + static_assert!(::core::mem::size_of::<$storage>() <=3D $stride); + + $crate::register!(@bitfield $(#[$attr])* $vis struct $name($storag= e) { $($fields)* }); + $crate::register!(@io_base $name($storage) @ $offset); + $crate::register!( + @io_relative_array $vis $name($storage) [ $size, stride =3D $s= tride ] @ $base + $offset + ); + }; + + // Shortcut for contiguous array of relative registers (stride =3D=3D = size of element). + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) [ $size:= expr ] + @ $base:ident + $offset:literal { $($fields:tt)* } + ) =3D> { + $crate::register!( + $(#[$attr])* $vis $name($storage) [ $size, stride =3D ::core::= mem::size_of::<$storage>() ] + @ $base + $offset { $($fields)* } + ); + }; + + // Creates an alias of register `idx` of relative array of registers `= alias` with its own + // fields. + ( + @reg $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty) + =3D> $base:ident + $alias:ident [ $idx:expr ] { $($fields:tt)*= } + ) =3D> { + static_assert!($idx < <$alias as $crate::io::register::RegisterArr= ay>::SIZE); + + $crate::register!(@bitfield $(#[$attr])* $vis struct $name($storag= e) { $($fields)* }); + $crate::register!( + @io_base $name($storage) @ + <$alias as $crate::io::register::Register>::OFFSET + + $idx * <$alias as $crate::io::register::RegisterArray>::ST= RIDE + ); + $crate::register!(@io_relative $vis $name($storage) @ $base); + }; + + // Generates the bitfield for the register. + // + // `#[allow(non_camel_case_types)]` is added since register names typi= cally use + // `SCREAMING_CASE`. + ( + @bitfield $(#[$attr:meta])* $vis:vis struct $name:ident($storage:t= y) { $($fields:tt)* } + ) =3D> { + $crate::register!(@bitfield_core + #[allow(non_camel_case_types)] + $(#[$attr])* $vis $name $storage + ); + $crate::register!(@bitfield_fields $vis $name $storage { $($fields= )* }); + }; + + // Implementations shared by all registers types. + (@io_base $name:ident($storage:ty) @ $offset:expr) =3D> { + impl $crate::io::register::Register for $name { + type Storage =3D $storage; + + const OFFSET: usize =3D $offset; + } + }; + + // Implementations of fixed registers. + (@io_fixed $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty)) =3D> { + impl $crate::io::register::FixedRegister for $name {} + + $(#[$attr])* + $vis const $name: $crate::io::register::FixedRegisterLoc<$name> = =3D + $crate::io::register::FixedRegisterLoc::<$name>::new(); + }; + + // Implementations of relative registers. + (@io_relative $vis:vis $name:ident ($storage:ty) @ $base:ident) =3D> { + impl $crate::io::register::WithBase for $name { + type BaseFamily =3D $base; + } + + impl $crate::io::register::RelativeRegister for $name {} + }; + + // Implementations of register arrays. + (@io_array $vis:vis $name:ident ($storage:ty) [ $size:expr, stride =3D= $stride:expr ]) =3D> { + impl $crate::io::register::Array for $name {} + + impl $crate::io::register::RegisterArray for $name { + const SIZE: usize =3D $size; + const STRIDE: usize =3D $stride; + } + }; + + // Implementations of relative array registers. + ( + @io_relative_array $vis:vis $name:ident ($storage:ty) [ $size:expr= , stride =3D $stride:expr ] + @ $base:ident + $offset:literal + ) =3D> { + impl $crate::io::register::WithBase for $name { + type BaseFamily =3D $base; + } + + impl $crate::io::register::RegisterArray for $name { + const SIZE: usize =3D $size; + const STRIDE: usize =3D $stride; + } + + impl $crate::io::register::RelativeRegisterArray for $name {} + }; + + // Defines the wrapper `$name` type and its conversions from/to the st= orage type. + (@bitfield_core $(#[$attr:meta])* $vis:vis $name:ident $storage:ty) = =3D> { + $(#[$attr])* + #[repr(transparent)] + #[derive(Clone, Copy, PartialEq, Eq)] + $vis struct $name { + inner: $storage, + } + + #[allow(dead_code)] + impl $name { + /// Creates a bitfield from a raw value. + #[inline(always)] + $vis const fn from_raw(value: $storage) -> Self { + Self{ inner: value } + } + + /// Turns this bitfield into its raw value. + /// + /// This is similar to the [`From`] implementation, but is sho= rter to invoke in + /// most cases. + #[inline(always)] + $vis const fn into_raw(self) -> $storage { + self.inner + } + } + + // SAFETY: `$storage` is `Zeroable` and `$name` is transparent. + unsafe impl ::pin_init::Zeroable for $name {} + + impl ::core::convert::From<$name> for $storage { + #[inline(always)] + fn from(val: $name) -> $storage { + val.into_raw() + } + } + + impl ::core::convert::From<$storage> for $name { + #[inline(always)] + fn from(val: $storage) -> $name { + Self::from_raw(val) + } + } + }; + + // Definitions requiring knowledge of individual fields: private and p= ublic field accessors, + // and `Debug` implementation. + (@bitfield_fields $vis:vis $name:ident $storage:ty { + $($(#[doc =3D $doc:expr])* $hi:literal:$lo:literal $field:ident + $(?=3D> $try_into_type:ty)? + $(=3D> $into_type:ty)? + ; + )* + } + ) =3D> { + #[allow(dead_code)] + impl $name { + $( + $crate::register!(@private_field_accessors $vis $name $storage : $= hi:$lo $field); + $crate::register!( + @public_field_accessors $(#[doc =3D $doc])* $vis $name $storag= e : $hi:$lo $field + $(?=3D> $try_into_type)? + $(=3D> $into_type)? + ); + )* + } + + $crate::register!(@debug $name { $($field;)* }); + }; + + // Private field accessors working with the exact `Bounded` type for t= he field. + ( + @private_field_accessors $vis:vis $name:ident $storage:ty : $hi:tt= :$lo:tt $field:ident + ) =3D> { + ::kernel::macros::paste!( + $vis const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive =3D $lo..=3D$hi; + $vis const [<$field:upper _MASK>]: $storage =3D + ((((1 << $hi) - 1) << 1) + 1) - ((1 << $lo) - 1); + $vis const [<$field:upper _SHIFT>]: u32 =3D $lo; + ); + + ::kernel::macros::paste!( + fn [<__ $field>](self) -> + ::kernel::num::Bounded<$storage, { $hi + 1 - $lo }> { + // Left shift to align the field's MSB with the storage MSB. + const ALIGN_TOP: u32 =3D $storage::BITS - ($hi + 1); + // Right shift to move the top-aligned field to bit 0 of the s= torage. + const ALIGN_BOTTOM: u32 =3D ALIGN_TOP + $lo; + + // Extract the field using two shifts. `Bounded::shr` produces= the correctly-sized + // output type. + let val =3D ::kernel::num::Bounded::<$storage, { $storage::BIT= S }>::from( + self.inner << ALIGN_TOP + ); + val.shr::() + } + + const fn [<__with_ $field>]( + mut self, + value: ::kernel::num::Bounded<$storage, { $hi + 1 - $lo }>, + ) -> Self + { + const MASK: $storage =3D <$name>::[<$field:upper _MASK>]; + const SHIFT: u32 =3D <$name>::[<$field:upper _SHIFT>]; + + let value =3D value.get() << SHIFT; + self.inner =3D (self.inner & !MASK) | value; + + self + } + ); + }; + + // Public accessors for fields infallibly (`=3D>`) converted to a type. + ( + @public_field_accessors $(#[doc =3D $doc:expr])* $vis:vis $name:id= ent $storage:ty : + $hi:literal:$lo:literal $field:ident =3D> $into_type:ty + ) =3D> { + ::kernel::macros::paste!( + + $(#[doc =3D $doc])* + #[doc =3D "Returns the value of this field."] + #[inline(always)] + $vis fn $field(self) -> $into_type + { + self.[<__ $field>]().into() + } + + $(#[doc =3D $doc])* + #[doc =3D "Sets this field to the given `value`."] + #[inline(always)] + $vis fn [](self, value: $into_type) -> Self + { + self.[<__with_ $field>](value.into()) + } + + ); + }; + + // Public accessors for fields fallibly (`?=3D>`) converted to a type. + ( + @public_field_accessors $(#[doc =3D $doc:expr])* $vis:vis $name:id= ent $storage:ty : + $hi:tt:$lo:tt $field:ident ?=3D> $try_into_type:ty + ) =3D> { + ::kernel::macros::paste!( + + $(#[doc =3D $doc])* + #[doc =3D "Returns the value of this field."] + #[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>]().try_into() + } + + $(#[doc =3D $doc])* + #[doc =3D "Sets this field to the given `value`."] + #[inline(always)] + $vis fn [](self, value: $try_into_type) -> Self + { + self.[<__with_ $field>](value.into()) + } + + ); + }; + + // Public accessors for fields not converted to a type. + ( + @public_field_accessors $(#[doc =3D $doc:expr])* $vis:vis $name:id= ent $storage:ty : + $hi:tt:$lo:tt $field:ident + ) =3D> { + ::kernel::macros::paste!( + + $(#[doc =3D $doc])* + #[doc =3D "Returns the value of this field."] + #[inline(always)] + $vis fn $field(self) -> + ::kernel::num::Bounded<$storage, { $hi + 1 - $lo }> + { + self.[<__ $field>]() + } + + $(#[doc =3D $doc])* + #[doc =3D "Sets this field to the compile-time constant `VALUE`."] + #[inline(always)] + $vis const fn [](self) = -> Self { + self.[<__with_ $field>]( + ::kernel::num::Bounded::<$storage, { $hi + 1 - $lo }>::new= ::() + ) + } + + $(#[doc =3D $doc])* + #[doc =3D "Sets this field to the given `value`."] + #[inline(always)] + $vis fn []( + self, + value: T, + ) -> Self + where T: Into<::kernel::num::Bounded<$storage, { $hi + 1 - $lo= }>>, + { + self.[<__with_ $field>](value.into()) + } + + $(#[doc =3D $doc])* + #[doc =3D "Tries to set this field to `value`, returning an error = if it is out of range."] + #[inline(always)] + $vis fn []( + self, + value: T, + ) -> ::kernel::error::Result + where T: ::kernel::num::TryIntoBounded<$storage, { $hi + 1 - $= lo }>, + { + Ok( + self.[<__with_ $field>]( + value.try_into_bounded().ok_or(::kernel::error::code::= EOVERFLOW)? + ) + ) + } + + ); + }; + + // `Debug` implementation. + (@debug $name:ident { $($field:ident;)* }) =3D> { + impl ::kernel::fmt::Debug for $name { + fn fmt(&self, f: &mut ::kernel::fmt::Formatter<'_>) -> ::kerne= l::fmt::Result { + f.debug_struct(stringify!($name)) + .field("", &::kernel::prelude::fmt!("{:#x}", self= .inner)) + $( + .field(stringify!($field), &self.$field()) + )* + .finish() + } + } + }; +} --=20 2.53.0 From nobody Thu Apr 2 20:26:43 2026 Received: from DM1PR04CU001.outbound.protection.outlook.com (mail-centralusazon11010006.outbound.protection.outlook.com [52.101.61.6]) (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 82FD026ED41; Sat, 14 Mar 2026 01:07:06 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.61.6 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450427; cv=fail; b=bh1F3Zo16Q61eOHghxBc/enemfS68blNJZTRGNRZ+O0RcfFXxoPrMjS/leD7WrkoizlWyOTPrB41CFB3ncfCNhbT6d9osRRB5vuv4NJZML0ZilKj3A61LyPGGh4zByYE+UTfoL61CRmdYgngQ5Hm5y+BA16an4KnpR6696kAyEc= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450427; c=relaxed/simple; bh=jUS+WDEdkb7fBsUt+aWytxaHsjIvbx91v8Avu+9st3I=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=K9rvAOpUJW/wZwluSsfKr3phph1PWzznc3OfXTm+HbiY3lEBRAFczKkZ8Vcj/CdPu2/h3Xma838BTu8tiE0xTFGExpZb9fcU/CJvh4jP14827vTNm+p5MN+3aKa6KlEOkco5tvoVmXtrnd2Mr5BLtKaRnrbrjXSHdgZUyEM4MQE= 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=cQeY/J4Y; arc=fail smtp.client-ip=52.101.61.6 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="cQeY/J4Y" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=AEWp//FmV5e2Ts0QE1ZEtoaSJlhofMxjH5YI+9jG9NQkTiywRh7zhaa09CJ57W8V1GzMc4c5rGxJSmpsMyiUMFs/MX+8cpCzt2uqDD/4UEtm1I3C82zpasMtpnkt62cjVWnPYZed+uBAgU/FOoCHJcrdxaFwk7fHDcXbjEhcKoanPDlNPozDrodK2uzfb73cUjBsQ6ldqjo7vglbYst2sKwa1xWdxcxBnDZAJVXyIjMXpjAHvFw0tQY2z+xDaqv7XbzL2+6Vu9gIj0FTDnhK8uPEukZ6Hvvi6s/zY/OeUsaXbBWCLrANvZsgLwWfRWoQ92Zqq26yZyyA4pAl5y3LiQ== 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=SCGv0Tnx5fvu6KFdHYc6naQ3oJiYODv2NfTXktgt6/Q=; b=KkTK1NHX6VGfQyg44BLrKJO0t8d/Kw1c7U4+TeY7WMzFgf+LRFibrnesgkSNwzCeCllriaEJPCJRTdAsKR6hCmORs+QPJD924BY8f1GE+1RYEoWQ7CNcoyRqhnVsjp377lSkamnVQGv5XgzmgF3EJG7S71Izo7UiHOYs+Aixs8FGqNeNUxGtKiPZiQv02izvKJL2G1DsMCuu3K9iDMCkw0xblXWTwDujVCAka98r6h/NNly4BmWOJZdBSrGInLljokozIDPacLcqD3GFi/ttAOE91tbpCO5vp+PvqX07wexpigzP6+nMLkOyJ2Ft6GIG7JZFRxgrBOdDnYoUcMsn2g== 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=SCGv0Tnx5fvu6KFdHYc6naQ3oJiYODv2NfTXktgt6/Q=; b=cQeY/J4YLIsa2GyOqLjKIicrFkwF4iS2z77oE7tfBuYpNmyTamIMaq+U8mAgOtaMQjiR6r8A03HZgLsiMrOQL0YN8tKMOqF3RXMrflkjXZ9SENyYK2xWhm5+u694TZFC0x1a9fJVi6mT7e9NhnBQeoUpfWXiyJ1NxYoepjqEbhjGS9sMxLwKIMJ6dPaTCegWl725lbZ749tR9H2dQW23q2tLQMFQ1n9J/Is9NyRNAHyJ56HvlZWxbdMF84npJymK5NZF2xzin4+bc/Dl2cb9Gky88OiUuaALQ8WU8jPeY+zYHkO9MW03h0kaEkwaFvIHD4D33+yOQeNcURmSXrMupg== 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 BY5PR12MB4033.namprd12.prod.outlook.com (2603:10b6:a03:213::22) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9723.6; Sat, 14 Mar 2026 01:06:59 +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.9723.000; Sat, 14 Mar 2026 01:06:59 +0000 From: Alexandre Courbot Date: Sat, 14 Mar 2026 10:06:18 +0900 Subject: [PATCH v9 08/10] rust: io: introduce `write_reg` and `LocatedRegister` Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260314-register-v9-8-86805b2f7e9d@nvidia.com> References: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> In-Reply-To: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> To: Danilo Krummrich , Alice Ryhl , Daniel Almeida , Miguel Ojeda , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Boqun Feng Cc: Yury Norov , John Hubbard , Alistair Popple , Joel Fernandes , Timur Tabi , Edwin Peer , Eliot Courtney , Dirk Behme , Steven Price , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alexandre Courbot X-Mailer: b4 0.14.3 X-ClientProxiedBy: TYCPR01CA0029.jpnprd01.prod.outlook.com (2603:1096:405:1::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_|BY5PR12MB4033:EE_ X-MS-Office365-Filtering-Correlation-Id: e9ca1dbd-bd82-499e-6ba6-08de8165fe36 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|376014|7416014|10070799003|921020|22082099003|56012099003|18002099003; X-Microsoft-Antispam-Message-Info: 7dTbP9NNzCG8zeB4ixvYzCcDHV136ih8b512hyjn974anH264cbFNy3kP+uXg6CaDm0d/kMhL+GHei+OSM4SzqneLg0JaQCdFhpVEog4S+3+2fjXe9YfmtPz7saCvWOD5aU2cY+lNFWc1ym3f1l1kHowzzFfPMi0RSXRBQYEoc7GXufMlKdOkcP6nKqFgQf4Tw+Uk8O4fnUYiT8aLVCQVtSl0XvwMuedAIyzDAFLpnGYW8idq/ftfjWHe8VQFuvsOLKc1swPwiyqwhALDg3qYDJTJAqLJ41PAj+EAYEDpbsx2rW2apgzRbVu1TOz88KhBfM0gBEWl1osx03D3frvVN5X1RAT+3TmEqHvwrFJlot04s2ZWPC0iR6xmWrieRVTCnonqaKL3U70JRZdwLruXKRJpg0zwREDsqsc3gFdq/wpPUsWBSSJJ+WlTjLarm6zRzmGHZG9UY+f5KD95S+llLxdeMzfJ1Hf+DvDXIDFO0+iUSSltVavf4OCF5cHrl0QdxqAAX0UHlhAEdcrIdUTrDasWHHT7C+gr4mXxHExblAkuLdlc+jR7s0DdfZudeVIMKLGFo3BUurMPn3J7It0Loq7N/9q5i/8l5YAFQ6WDww5JyK44WFayR5y+kIVuWQ6xXCjGst6KHQs3tCODBvqJ+RbmAeweuzwFbrQU+OuIPKGMaAOC6f4FfiaAbOUCnXx/WZrfGoxdvvRc4OaMsfRff5tilq3+yNIAhX+t2YU5MYZV/lrfcKughZKpKWob0dpUTq4Vd8Qyk+JvQTGDvvp+Q== 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)(366016)(1800799024)(376014)(7416014)(10070799003)(921020)(22082099003)(56012099003)(18002099003);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 2 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?Mi9zM1dpNEdxTTZZZDBQYWp0blgzUjFaWFBmZkNGWi9JRmw2NlMvcmhrS0Jx?= =?utf-8?B?VHFSYlFzMHUxakhzaTZpKzEwQmJ6R0tibFQ3YmhqSFJkRDYwWWk5Z09Xb2Fl?= =?utf-8?B?azAyU21PY0V0MzRYSTYrUXNxUDlsc3kyREgyei9MMUVZYTRUejVHT3p0T3JI?= =?utf-8?B?SDlJckZncGx3N1g4K3VoVUU4Z3dBNE9USmQ2cFZzQk1zaVpxem1YMlYvNXpT?= =?utf-8?B?TWpOMGZXbVpvejdOVU5FblRBRjQwYzY0VkdJMnpMazRRUFBVZEFBV2FXTXla?= =?utf-8?B?eHdlSW9IOHdEc0pZRmovaU1yRzg4cGVyZUxiSHdjVGRjcStZUEZUS0lOQjdK?= =?utf-8?B?ck1MT1o0ZDZJNloxTEF5VWgvbEhKQjU5RFliMlZiRlB3dWNCUWxiWjk0NWYr?= =?utf-8?B?U3NCTllsSjNMNzA0UkJQNzZGVUJiOGprQUdWV3dWdmIwV0hHRkJVajNYaFFk?= =?utf-8?B?cnUzMXo3SzlXelA4QUtYYkRrclBCWWhTMzZMdGR6akkyQTU4WEUyT09vYWxh?= =?utf-8?B?Qk5yWVFobUtjM3I5YS9ZMnBGOEM3QS9rRDZiTmFLVzRTQzlpVjlueGhjRVkz?= =?utf-8?B?YmdDeDZpVEFldC9DWW9GMDh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-1: VTo2SMBubogYzQ== X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: e9ca1dbd-bd82-499e-6ba6-08de8165fe36 X-MS-Exchange-CrossTenant-AuthSource: CH2PR12MB3990.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 14 Mar 2026 01:06:59.1295 (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: D1TQeqEVcIX787BEIOoSIRiVOtwhClOwbhlU/EOImFj+s1+ab15+WEVKCD1OHdCt9f+A7hrWQ/D16QpwH8Hh8w== X-MS-Exchange-Transport-CrossTenantHeadersStamped: BY5PR12MB4033 Some I/O types, like fixed address registers, carry their location alongside their values. For these types, the regular `Io::write` method can lead into repeating the location information twice: once to provide the location itself, another time to build the value. We are also considering supporting making all register values carry their full location information for convenience and safety. Add a new `Io::write_reg` method that takes a single argument implementing `LocatedRegister`, a trait that decomposes implementors into a `(location, value)` tuple. This allows write operations on fixed offset registers to be done while specifying their name only once. Signed-off-by: Alexandre Courbot --- rust/kernel/io.rs | 70 ++++++++++++++++++++++++++++++++++++++++++= ++++ rust/kernel/io/register.rs | 35 +++++++++++++++++++++-- 2 files changed, 103 insertions(+), 2 deletions(-) diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index bfea30a9acdf..24e6b48b6582 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -17,6 +17,8 @@ pub use crate::register; pub use resource::Resource; =20 +use register::LocatedRegister; + /// Physical address type. /// /// This is a type alias to either `u32` or `u64` depending on the config = option @@ -473,6 +475,40 @@ fn try_write(&self, location: L, value: T) -> Re= sult Ok(()) } =20 + /// Generic fallible write of a fully-located register value. + /// + /// # Examples + /// + /// Tuples carrying a location and a value can be used with this metho= d: + /// + /// ```no_run + /// use kernel::io::{ + /// register, + /// Io, + /// Mmio, + /// }; + /// + /// register! { + /// FIFO_OUT(u32) @ 0x100 {} + /// } + /// + /// fn do_write_reg(io: &Mmio) -> Result { + /// // `FIFO_OUT` provides us the location of the write operation. + /// io.try_write_reg(FIFO_OUT::from(10)) + /// } + /// ``` + #[inline(always)] + fn try_write_reg(&self, value: V) -> Result + where + L: IoLoc, + V: LocatedRegister, + Self: IoCapable, + { + let (location, value) =3D value.into_io_op(); + + self.try_write(location, value) + } + /// Generic fallible update with runtime bounds check. /// /// Note: this does not perform any synchronization. The caller is res= ponsible for ensuring @@ -578,6 +614,40 @@ fn write(&self, location: L, value: T) unsafe { self.io_write(io_value, address) } } =20 + /// Generic infallible write of a fully-located register value. + /// + /// # Examples + /// + /// Tuples carrying a location and a value can be used with this metho= d: + /// + /// ```no_run + /// use kernel::io::{ + /// register, + /// Io, + /// Mmio, + /// }; + /// + /// register! { + /// FIFO_OUT(u32) @ 0x100 {} + /// } + /// + /// fn do_write_reg(io: &Mmio<0x1000>) { + /// // `FIFO_OUT` provides us the location of the write operation. + /// io.write_reg(FIFO_OUT::from(10)); + /// } + /// ``` + #[inline(always)] + fn write_reg(&self, value: V) + where + L: IoLoc, + V: LocatedRegister, + Self: IoKnownSize + IoCapable, + { + let (location, value) =3D value.into_io_op(); + + self.write(location, value) + } + /// Generic infallible update with compile-time bounds check. /// /// Note: this does not perform any synchronization. The caller is res= ponsible for ensuring diff --git a/rust/kernel/io/register.rs b/rust/kernel/io/register.rs index 40085953c831..b26dc2400009 100644 --- a/rust/kernel/io/register.rs +++ b/rust/kernel/io/register.rs @@ -80,10 +80,10 @@ //! .with_const_minor_revision::<10>() //! // Run-time value. //! .with_vendor_id(obtain_vendor_id()); -//! io.write((), new_boot0); +//! io.write_reg(new_boot0); //! //! // Or, build a new value from zero and write it: -//! io.write((), BOOT_0::zeroed() +//! io.write_reg(BOOT_0::zeroed() //! .with_const_major_revision::<3>() //! .with_const_minor_revision::<10>() //! .with_vendor_id(obtain_vendor_id()) @@ -379,6 +379,34 @@ fn offset(self) -> usize { } } =20 +/// Trait implemented by items that contain both a register value and the = absolute I/O location at +/// which to write it. +/// +/// Implementors can be used with [`Io::write_reg`](super::Io::write_reg). +pub trait LocatedRegister { + /// Register value to write. + type Value: Register; + /// Full location information at which to write the value. + type Location: IoLoc; + + /// Consumes `self` and returns a `(location, value)` tuple describing= a valid I/O write + /// operation. + fn into_io_op(self) -> (Self::Location, Self::Value); +} + +impl LocatedRegister for T +where + T: FixedRegister, +{ + type Location =3D FixedRegisterLoc; + type Value =3D T; + + #[inline(always)] + fn into_io_op(self) -> (FixedRegisterLoc, T) { + (FixedRegisterLoc::new(), self) + } +} + /// Defines a dedicated type for a register, including getter and setter m= ethods for its fields and /// methods to read and write it from an [`Io`](kernel::io::Io) region. /// @@ -433,6 +461,9 @@ fn offset(self) -> usize { /// // The location of fixed offset registers is already contained in thei= r type. Thus, the /// // `location` argument of `Io::write` is technically redundant and can= be replaced by `()`. /// io.write((), val2); +/// +/// // Or, the single-argument `Io::write_reg` can be used. +/// io.write_reg(val2); /// # } /// /// ``` --=20 2.53.0 From nobody Thu Apr 2 20:26:43 2026 Received: from DM1PR04CU001.outbound.protection.outlook.com (mail-centralusazon11010006.outbound.protection.outlook.com [52.101.61.6]) (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 1F62A282F3F; Sat, 14 Mar 2026 01:07:08 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.61.6 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450429; cv=fail; b=Rf8dTc3RrmhNF7qdtFweZG5PoiHEGY3OIv4bQkQffgVxpGk8OMdZ0TO+fL2/bESB0pcrGJBa67jBtmsCwV7ekuYmi4gPhBlvnfOWB1chIJ7QLPQJM+NJ8An9cG1MDPvW8svBtcAaNB3KlpCqnoFW4qYYi72Ik3qooXF+RBl2GEo= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450429; c=relaxed/simple; bh=KhOv4tE1lYpDhF2oVds2irOaJFJNQ2/ak9MTyexcx/8=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=Dy7kNx2JAhVoxQ8g2OJapesB89PJEeiXkS2S/KGZxi6h8sD6QLXZPOzoABZPJ+mZ6nueQWKCygEYcnDTRPH4byEJa2pjpn/yhwllaEIxjmwB0Uyy3ZsgnR1Lz1xoFARyMAELJqCUrv2C4JPpHK8REmxduMdkL06tc/alYOmteY4= 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=j5T0uqag; arc=fail smtp.client-ip=52.101.61.6 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="j5T0uqag" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=On41pa6a51QhtLGmNozQftqMm/y80oRzPgVDHdBUAS3HnKhigyoMQJJgrnmDBmhQLvBdSmKeloi0z2IHVUrQDn8jhqhhGfrqovsTLCDVEQ9fiLnWLFNAk4pYJzRZoRGeRSX/Vq2YUJAXfmlyIWX448j6UilOEfhJKirRO8MjJubXEPKdlrTUdIy31EM6mizYG5OKYM8GUUvs9ZVRp+YU84FWq9I2gUs3coZ8nZ3FgYZEMThZfPIA2kjwwQiJtuSB+3x27Y8KZmZf8q632PY+PtTHsPJRpiYRenTJviPxFmUCw+xjck7jQNaDKQfVYMZc/IjBQY1zxPQ1aMhF0heNPg== 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=4DGns6Vo2AA2s8S5lqAkHeKb8AQJwbWd+0VNITWBXbg=; b=HKAXFFpCI3CcnKTRIBEsCL+hOQl6P+Pmx0A7suZOPlHPj5P87w9QfsZnrV76lttjC8/vTiHujvklqcuJQP41UCvX1jCOT/4sFqEEnvTK4XUMuTW22xwVOIwXydbX970KxPd9LJG6IWNivn255bTsM3lvr5ilPJv18G5zgZ1IctgIg1u6zERddx5wj1wezs8ee6I8xvgoTrwsvHTM8xvkWNweaAy3ehuXwK9mkwc3HmN1MnkBdQpqkvLF36dkbUAy65wLZlgULu0qBSc2DmFX9c5Jqka/PDQMzsN1hPKPsYEdYgSDJF9HE0hCSJbS92Gy5D21gKUCmxUCtW24meLlzA== 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=4DGns6Vo2AA2s8S5lqAkHeKb8AQJwbWd+0VNITWBXbg=; b=j5T0uqagLM5knLx7brQ3H2f1jWjugXQhzE5GiLJSPmmXYNcQUcd173dJvvw91xaw+Z3zFevUEDvKCUzZcpVkwecSbeBV6+FhtW8MfCVMz76W8+jPiDqW1pIJzlw2FWShUxq8rF4TjqKXS96VwzyHs363+BEqtLglktbA8aFmnn92hBHbxeuwoxOEUrXyIj0XK9EKtjlJ/xPwfjENaqmbDeCaKjrQ3F/EStUYXvKpN+ldO26UOrfDIbvlxtCCOlqaFLNkypbJmRh/kPJE7gWuZ7BEu7VGF7q6qxkYuX9R3/nCdsxC4ChJH9yqIDoGbaOpKjhv/7HzGouf0rxSCAw+Ow== 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 BY5PR12MB4033.namprd12.prod.outlook.com (2603:10b6:a03:213::22) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9723.6; Sat, 14 Mar 2026 01:07:03 +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.9723.000; Sat, 14 Mar 2026 01:07:03 +0000 From: Alexandre Courbot Date: Sat, 14 Mar 2026 10:06:19 +0900 Subject: [PATCH v9 09/10] sample: rust: pci: use `register!` macro Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260314-register-v9-9-86805b2f7e9d@nvidia.com> References: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> In-Reply-To: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> To: Danilo Krummrich , Alice Ryhl , Daniel Almeida , Miguel Ojeda , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Boqun Feng Cc: Yury Norov , John Hubbard , Alistair Popple , Joel Fernandes , Timur Tabi , Edwin Peer , Eliot Courtney , Dirk Behme , Steven Price , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alexandre Courbot , Zhi Wang X-Mailer: b4 0.14.3 X-ClientProxiedBy: TY4PR01CA0056.jpnprd01.prod.outlook.com (2603:1096:405:372::15) 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_|BY5PR12MB4033:EE_ X-MS-Office365-Filtering-Correlation-Id: 5b5824d9-ef9b-4f19-7a46-08de81660050 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|376014|7416014|10070799003|921020|22082099003|56012099003|18002099003; X-Microsoft-Antispam-Message-Info: LD6PALmNdgjAnumOqhYzPT4vHC+P1zqlU/lsYOZOfxjZ38GvEDbFj8TW+tz68tAKj8P9k2+O46BO1Yz1IGbUB7h2OVCWmK41GhMEbH5kGg3zAGVfKFF8s/Gn68TVC1E4m93OmS0BCt3pQ0k1pBlN5PPGkqu++TmXLityE2aGlU0Ns9eO4R5Wl3WhVuJs6mkv7/3LvUvGgNl7Ydk21f3NeoQ2JI3x9GbKgsHhddOCngF7dPgAt4lUzGatxgkuHbTzhzwqmmulli6MGrKk+4HnXMZDHGvqr52+dMO+SKHM1w97ODy5tQ8VWibrhMXlknBetw4+lx7k+MqQhheWSXkPc5IwND3re4PzrE99CApSlc1qiU5jNKI6tY3rFn5d7DFWusELOB8qsf6xJr5mfUVYWSknZyRsLkj416yq4F2oWIVI2oc02K2vRUIAYUwIVXtgjjUQgs8UYolBkgRbkCgWzX4E/fWKYTGpQ38oL1tglrieZuG/cl6uZI41hUl3g0oa9jLkrBXOIO5RY90mI3NELTVzsIiMTx4eeZs06l64rl9PfRNI6wwnHR161/Vt5lH/L7VFBShMKfNmto4AK42YAybLrruRshk7Hj5Fc8kQRXPEy9paE2vrbSUJnwmLgtdF6HRNC3A47QqVN5bC4+m/8WMNlfSwUX9lyGR1waD84R3GtX5gcGQs4YL+81ALwQp4iBrQHj1qgWgydjlrCRI9dr4Lk6ukjjG3yxH21mYpNZ7gewqUVUWJ5snczYTGDt76Qltt0/TwruGm9MkuE6926A== 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)(366016)(1800799024)(376014)(7416014)(10070799003)(921020)(22082099003)(56012099003)(18002099003);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 2 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?WTNENFNnaVJzc2tsUjN0UVJhaTFQd000R1pWN1AzSnBydlZlQVlMaXB4RTRJ?= =?utf-8?B?UTZRWGV4U2MzVlFHZ0Voc1UvVU9vaWdqSWxBY2JKRUIyOThnUVA3R3NEdmRn?= =?utf-8?B?YnljOHdOWlAzeVBYK3lsWEFrWkJBc1Z3dDdiazZNeW9FQ1U1d3NadEM2T3Uw?= =?utf-8?B?Rk1ydkluQkE0YmlzOFNZWmNmZk1KTmJ6aUJlcHpsc2tReHF2K2lwL0Vqazh2?= =?utf-8?B?cVRBZnhkUSs5QnNXRjZXNm1wNGFKUFEwVktVOFA1WGxIa0t5MmU3YTNUbnR6?= =?utf-8?B?a1RncnZaN0k1NGhFNS9YTE1Oc3crK01lMGFpN0IvUUFWUVdFSEwyQWdtY1hB?= =?utf-8?B?bWZJQTVyN3RrNmg1cDY1V1ZWcWVCVXNhcDV1cTJzWUFKais0dnQ5VUEwMEFl?= =?utf-8?B?VW9TVG1kTUVDeGliY0xLekFYblBRbnQrK0JLV0pGb2p3ckI0L05JODFRa3NG?= =?utf-8?B?cWxZM1FGN1FnZURhTkYxWDVuOWhnS0RxeHRKNHVpblBBWHlENHJFOG55Nm9M?= =?utf-8?B?NFR0YVNTb3RWRmhsNjNnZjFacGJ3Q2lnR2FNNU8wNlhTMjQyQWZOLytFMnEv?= =?utf-8?B?dDlONGViQzhOVFcyWFNuMlhMV0FTTXIydVFyU0JZVjB5QUFFWXczMkR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KS/3ICwQEw== X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 5b5824d9-ef9b-4f19-7a46-08de81660050 X-MS-Exchange-CrossTenant-AuthSource: CH2PR12MB3990.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 14 Mar 2026 01:07:02.9382 (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: bHQqwzRmOnGqPN+6qOHKs5vMKuZOwlx7pKC3fbgOBxRoE9FM46vVGjDXCA6Gc35Hye3MC7ILyEGy8RGKMwc6ew== X-MS-Exchange-Transport-CrossTenantHeadersStamped: BY5PR12MB4033 Convert the direct IO accesses to properly defined registers. Tested-by: Zhi Wang Signed-off-by: Alexandre Courbot --- samples/rust/rust_driver_pci.rs | 84 +++++++++++++++++++++++++++++++------= ---- 1 file changed, 64 insertions(+), 20 deletions(-) diff --git a/samples/rust/rust_driver_pci.rs b/samples/rust/rust_driver_pci= .rs index d3d4a7931deb..064f78b7f5b9 100644 --- a/samples/rust/rust_driver_pci.rs +++ b/samples/rust/rust_driver_pci.rs @@ -8,27 +8,58 @@ device::Bound, device::Core, devres::Devres, - io::Io, + io::{ + register, + register::Array, + Io, // + }, + num::Bounded, pci, prelude::*, sync::aref::ARef, // }; =20 -struct Regs; +mod regs { + use super::*; =20 -impl Regs { - const TEST: usize =3D 0x0; - const OFFSET: usize =3D 0x4; - const DATA: usize =3D 0x8; - const COUNT: usize =3D 0xC; - const END: usize =3D 0x10; + register! { + pub(super) TEST(u8) @ 0x0 { + 7:0 index =3D> TestIndex; + } + + pub(super) OFFSET(u32) @ 0x4 { + 31:0 offset; + } + + pub(super) DATA(u8) @ 0x8 { + 7:0 data; + } + + pub(super) COUNT(u32) @ 0xC { + 31:0 count; + } + } + + pub(super) const END: usize =3D 0x10; } =20 -type Bar0 =3D pci::Bar<{ Regs::END }>; +type Bar0 =3D pci::Bar<{ regs::END }>; =20 #[derive(Copy, Clone, Debug)] struct TestIndex(u8); =20 +impl From> for TestIndex { + fn from(value: Bounded) -> Self { + Self(value.into()) + } +} + +impl From for Bounded { + fn from(value: TestIndex) -> Self { + value.0.into() + } +} + impl TestIndex { const NO_EVENTFD: Self =3D Self(0); } @@ -54,40 +85,53 @@ struct SampleDriver { impl SampleDriver { fn testdev(index: &TestIndex, bar: &Bar0) -> Result { // Select the test. - bar.write8(index.0, Regs::TEST); + bar.write_reg(regs::TEST::zeroed().with_index(*index)); =20 - let offset =3D bar.read32(Regs::OFFSET) as usize; - let data =3D bar.read8(Regs::DATA); + let offset =3D bar.read(regs::OFFSET).into_raw() as usize; + let data =3D bar.read(regs::DATA).into(); =20 // Write `data` to `offset` to increase `count` by one. // // Note that we need `try_write8`, since `offset` can't be checked= at compile-time. bar.try_write8(data, offset)?; =20 - Ok(bar.read32(Regs::COUNT)) + Ok(bar.read(regs::COUNT).into()) } =20 fn config_space(pdev: &pci::Device) { let config =3D pdev.config_space(); =20 - // TODO: use the register!() macro for defining PCI configuration = space registers once it - // has been move out of nova-core. + // Some PCI configuration space registers. + register! { + VENDOR_ID(u16) @ 0x0 { + 15:0 vendor_id; + } + + REVISION_ID(u8) @ 0x8 { + 7:0 revision_id; + } + + BAR(u32)[6] @ 0x10 { + 31:0 value; + } + } + dev_info!( pdev, "pci-testdev config space read8 rev ID: {:x}\n", - config.read8(0x8) + config.read(REVISION_ID).revision_id() ); =20 dev_info!( pdev, "pci-testdev config space read16 vendor ID: {:x}\n", - config.read16(0) + config.read(VENDOR_ID).vendor_id() ); =20 dev_info!( pdev, "pci-testdev config space read32 BAR 0: {:x}\n", - config.read32(0x10) + config.read(BAR::at(0)).value() ); } } @@ -111,7 +155,7 @@ fn probe(pdev: &pci::Device, info: &Self::IdInfo)= -> impl PinInit(0, c"rust_= driver_pci"), + bar <- pdev.iomap_region_sized::<{ regs::END }>(0, c"rust_= driver_pci"), index: *info, _: { let bar =3D bar.access(pdev.as_ref())?; @@ -131,7 +175,7 @@ fn probe(pdev: &pci::Device, info: &Self::IdInfo)= -> impl PinInit, this: Pin<&Self>) { if let Ok(bar) =3D this.bar.access(pdev.as_ref()) { // Reset pci-testdev by writing a new test index. - bar.write8(this.index.0, Regs::TEST); + bar.write_reg(regs::TEST::zeroed().with_index(this.index)); } } } --=20 2.53.0 From nobody Thu Apr 2 20:26:43 2026 Received: from BN8PR05CU002.outbound.protection.outlook.com (mail-eastus2azon11011071.outbound.protection.outlook.com [52.101.57.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 5085C2517A5; Sat, 14 Mar 2026 01:07:22 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.57.71 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450446; cv=fail; b=uhGPDleEpJ0Ww5AuR70Gx2pCZvSE2HHcFYRXcWY2UGneH75ecHvArSP1idKxCyJxA7y8VhCqBTGFX04WdD2gTiJUKXYKB72oyizd3vCNUHoyOn1qt51Rb1tSws0SPcSLlM/Qlej6+g/DoJfMW9Xu9DF6n89vxXm9wZJKwn9rSIM= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1773450446; c=relaxed/simple; bh=WSuL7Cff+sG6+t0dxlqZ/c5IjCd3yXT6OFq9nGHfa30=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=oO3qL/SOZi77Z0JKlDMzxDmnGq5DZBKWU8AWE7ctm5hyVvoR2SewWL6UfuGEFMx7UUqWVLAZtP0LcOopymMSXsgfrJJ8Svkcxjj4an249N0egj/sp416lk4DEYTnqcpBpbO3bmkGQFDi2YC8i8PpZ/cSWj53pkITdxV6J3vfWO4= 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=O2ickR3j; arc=fail smtp.client-ip=52.101.57.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="O2ickR3j" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=NFnroBLJ4pts6W3qHjWlVmB8uosE32BwbqJDEDcZry5Qqi/EQnr2b5LdFR1NPY5U86/oLZbJrtnT+5EKU7Weu6gpMJqpFkBzJWxahpjil5m2Zky3x04rzxiodpTZ9NnnfYH4XJGI/CeBrU6y9+6jM4W4CkEkEhJQp40pKDRJybnAX/hsSHCinzatZ+RCNHE0HO7HYRIw0zeQ3tt19hl4qW+1eNF67hGgZ9Kt0loA43oVutMqd7QLvNoX8CRI94hb7+7gcUGHKx/4XwDz/fu9qKg8jsWqO4+sdhC787yhxsXYh3AK0FBiC/e2rAzWesacPYDgmMqaqxs8bmMNpqFC2g== 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=naqeIVfFZul1OKJcUBggfUhhgjJPKHzOmX41oecRCY0=; b=LnagQgAZTUdEzYn8Yy4gYPSxjj8TPzBXdO6tu1gVKpLX99uIhk9z7jjoeTMoiRAcR6GkMfoN8QeZYgxo85v0Gei5zCsaSju0kAyyw14eAuafzKl85GRa45Nu57jD8SUJvjj0AYE9v7mEHIntuq8KxdaTB+KbvCNQ+9XkpRbeOtWdNLObdPEu8B42L4dEyX3ojxTRoNzHXJW2jKTNjEVTiXAd5qfMro2cbY1bVxiNOG84PMOHhLRYTfc8YZKXdKey+LADME0zO7pr90bXZ/D3M11baTplss/A9vqcOUO1Z9sxnYVgQTqnUE2TMH8rNqzFj3VCJkvK5hIsftJY8xtI5g== 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=naqeIVfFZul1OKJcUBggfUhhgjJPKHzOmX41oecRCY0=; b=O2ickR3jh0CHRY2DgoTswyJw0Iz/+Gmi7P3T5kFZHGKwQQ0ULVTo6R23PwwhM2955gNd82uWvSA5Hxofj7eOBA5Mi87PONvD/momMTLXzD9chvasE5Y4X3X3G63hsUcr7HhjgKeF94KFSUROjBkcmVzngCMs9Ik8c8Lqkw0qB040z4i48x4PWaVt1PjmLKdRz74KTxkcM2ChnecNHC1rScLN+k6DX0DvFZwuc4i6eWZGGcwk+Xt+Ok2b0dvU9N9254nb6jXTe7wx/6CZ8M8Oq8jCD2cmvaMmucNcRBFSIQ2MSqke/gIYt4zp4csPc/DWYtKdLJsQQkj7+BnZif6yMw== 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 BY5PR12MB4033.namprd12.prod.outlook.com (2603:10b6:a03:213::22) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9723.6; Sat, 14 Mar 2026 01:07:06 +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.9723.000; Sat, 14 Mar 2026 01:07:06 +0000 From: Alexandre Courbot Date: Sat, 14 Mar 2026 10:06:20 +0900 Subject: [PATCH FOR REFERENCE v9 10/10] gpu: nova-core: use the kernel `register!` macro Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260314-register-v9-10-86805b2f7e9d@nvidia.com> References: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> In-Reply-To: <20260314-register-v9-0-86805b2f7e9d@nvidia.com> To: Danilo Krummrich , Alice Ryhl , Daniel Almeida , Miguel Ojeda , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Boqun Feng Cc: Yury Norov , John Hubbard , Alistair Popple , Joel Fernandes , Timur Tabi , Edwin Peer , Eliot Courtney , Dirk Behme , Steven Price , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alexandre Courbot X-Mailer: b4 0.14.3 X-ClientProxiedBy: TY4PR01CA0127.jpnprd01.prod.outlook.com (2603:1096:405:379::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_|BY5PR12MB4033:EE_ X-MS-Office365-Filtering-Correlation-Id: 6d4ea98f-2194-410e-f6f4-08de8166024a X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|376014|7416014|10070799003|921020|22082099003|56012099003|18002099003; X-Microsoft-Antispam-Message-Info: 6Imimyap34Hw9JgCDo2dkgv0v29Fj7ZZkUQ6s1gj4o37tT7RGM0od9XgoYNVfF7lSOkApwUCcu6HOHwTdA6M/0BcjebXaSRsNuzKmu/VX1JAScDuR+pqQLeoSxobnDlQBwgW8nWmU9C2qxMGrO7Z9gXXD1XI1MeuCbGbE5hiAgFcyQVRfFuS4jt0Mlv88UkI3vmXgP+rdjF8+e8HMJ6T44nFaxjxaxouNfT/KCRQxs9McwEepdUO4YD30r05PUIG+XYA7gPFVc0IjCLFRiUfDc83d0f8l0cfNzkuC1RP9MRkgoR7+zjI2dvmKOSPj2ZgFhN8lReWRxqB2S68LL1bqWZRqY3fK1SAyoId9wUHbBeOBKn/cRB2SLYO51t/dh/zaqQoyLb4N3wlypVf+mV85N2nNCkWCSLuaG4h8AulhJ9ofV5C1LdNsbWc2ot/i7FGg/OIOD8lHml6IeqvWPqf6D9beJdxS5SUp4vOwCD+q9Ott0/14GBo5LilJ3QFTH3n0vhjYnhORFnTIr66nBvWiU+2ax2RL4cvwCDbAYRvWS3L845Rd4dAauwZf8TKOGOwMtDG60T1IaqyR2WqMtZWW2YAB8WIrh/WjvU0a70O7YdGKHdaJHq/wzzmefiSNvYumrk0CacniHXF4RTgLNZV6kiKJJKsUAL3Ps2Z5TiK4DGvQUth8m/X8GFtoFmMz6RhWQLYUsP7zZ7w72dplnq7FMdifNULvwblHEIVg6JQvt+4gkeJ7SO2V8C2y6qwxnpg6URB5qxleatNDtMBpFagYL+ria85Jn89m9/TdTM73N8= 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)(366016)(1800799024)(376014)(7416014)(10070799003)(921020)(22082099003)(56012099003)(18002099003);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 2 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?a2VMVDUycVBpWEp5bHhuWGxlbFNQOEdlb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-8?B?bWgvbDl1QTJPRkt6V2VGVnY4RUtsRzhxa2VQMkxTdDlnV3NUd2Z6Z3FTaUZh?= =?utf-8?B?eFFzWXhQaGZ3SWNuZTF0NllRTjFBYkFQL1B0SlVKc245R05ZTXVUZUQ2SzRT?= =?utf-8?B?eTZuOXBUZm81UWVYUi95cStTaHVid0xQSWsvWXgwNFRMV25vYzF2RUVBbFZH?= =?utf-8?B?R0MzcW96TTBHUHBxU3cxbVVsSmpoSUtRQWc5YXZXdmViVlliaHArd1VQS09z?= =?utf-8?B?U0FZOEFDYm1QdG91TFRVbmR4R0tkdU9INWhmZk9RQjdIRzNjeEVWMHNHK25O?= =?utf-8?B?TE5iQjFEUWVsZWNKTG1FOWx0RmdIUm45aitsR3VQL0QzK3NmZkNvelZ1Q1o4?= =?utf-8?B?eTU2a3pUeU9pNnNNOFcyMWg5VlZpYnVQVGVQSCtzMWd2VFJXa3JDNzJhU29k?= =?utf-8?B?YmZGVTFWZklUTHdiSkxyN2hDS1BqU2Q1Mm9zeXV4dzQ0bk90dzJralFRTHJr?= =?utf-8?B?bXB4TGsrTDJJTVRHMm53eGJxVlQ1Rk5GaXE5dzBaeTJoTFF5R05UOHJodWVa?= =?utf-8?Q?cKpjnnv5lZuiEcCaaTorE5fIsL66aKszJoeWTOb8AdC2c?= X-MS-Exchange-AntiSpam-MessageData-1: LMCrneA9DVFeIQ== X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 6d4ea98f-2194-410e-f6f4-08de8166024a X-MS-Exchange-CrossTenant-AuthSource: CH2PR12MB3990.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 14 Mar 2026 01:07:06.2821 (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: PfRZZb8/ONqVct+3Hz1RNNhCjWSvNazqL3AtV50hvpwAITtJnToL3i/jrRTaSZ0eQZyF/Nw4yI63ORc/1nnabA== X-MS-Exchange-Transport-CrossTenantHeadersStamped: BY5PR12MB4033 Replace the nova-core internal `register!` macro by the one defined in the `kernel` crate and remove our own private implementations. Signed-off-by: Alexandre Courbot --- drivers/gpu/nova-core/falcon.rs | 333 +++++----- drivers/gpu/nova-core/falcon/gsp.rs | 25 +- drivers/gpu/nova-core/falcon/hal/ga102.rs | 70 +- drivers/gpu/nova-core/falcon/hal/tu102.rs | 12 +- drivers/gpu/nova-core/falcon/sec2.rs | 17 +- drivers/gpu/nova-core/fb.rs | 6 +- drivers/gpu/nova-core/fb/hal/ga100.rs | 37 +- drivers/gpu/nova-core/fb/hal/ga102.rs | 7 +- drivers/gpu/nova-core/fb/hal/tu102.rs | 17 +- drivers/gpu/nova-core/firmware/fwsec/bootloader.rs | 19 +- drivers/gpu/nova-core/gfw.rs | 11 +- drivers/gpu/nova-core/gpu.rs | 36 +- drivers/gpu/nova-core/gsp/boot.rs | 11 +- drivers/gpu/nova-core/gsp/cmdq.rs | 9 +- drivers/gpu/nova-core/regs.rs | 616 +++++++++-------- drivers/gpu/nova-core/regs/macros.rs | 739 -----------------= ---- 16 files changed, 676 insertions(+), 1289 deletions(-) diff --git a/drivers/gpu/nova-core/falcon.rs b/drivers/gpu/nova-core/falcon= .rs index 7097a206ec3c..f812c131d313 100644 --- a/drivers/gpu/nova-core/falcon.rs +++ b/drivers/gpu/nova-core/falcon.rs @@ -13,7 +13,15 @@ DmaAddress, DmaMask, // }, - io::poll::read_poll_timeout, + io::{ + poll::read_poll_timeout, + register::{ + RegisterBase, + WithBase, // + }, + Io, + }, + num::Bounded, prelude::*, sync::aref::ARef, time::Delta, @@ -30,7 +38,6 @@ IntoSafeCast, // }, regs, - regs::macros::RegisterBase, // }; =20 pub(crate) mod gsp; @@ -41,11 +48,11 @@ pub(crate) const MEM_BLOCK_ALIGNMENT: usize =3D 256; =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 { fn from(value: $enum_type) -> Self { - value as u8 + Bounded::from_expr(value as u32) } } }; @@ -53,10 +60,8 @@ fn from(value: $enum_type) -> Self { =20 /// Revision number of a falcon core, used in the [`crate::regs::NV_PFALCO= N_FALCON_HWCFG1`] /// register. -#[repr(u8)] -#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub(crate) enum FalconCoreRev { - #[default] Rev1 =3D 1, Rev2 =3D 2, Rev3 =3D 3, @@ -65,16 +70,16 @@ 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 { 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 value.get() { 1 =3D> Rev1, 2 =3D> Rev2, 3 =3D> Rev3, @@ -91,46 +96,38 @@ fn try_from(value: u8) -> Result { =20 /// Revision subversion number of a falcon core, used in the /// [`crate::regs::NV_PFALCON_FALCON_HWCFG1`] register. -#[repr(u8)] -#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub(crate) enum FalconCoreRevSubversion { - #[default] Subversion0 =3D 0, Subversion1 =3D 1, 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 { + fn from(value: Bounded) -> Self { use FalconCoreRevSubversion::*; =20 - let sub_version =3D match value & 0b11 { + match value.get() { 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 -/// Security model of a falcon core, used in the [`crate::regs::NV_PFALCON= _FALCON_HWCFG1`] -/// register. -#[repr(u8)] -#[derive(Debug, Default, Copy, Clone)] /// Security mode of the Falcon microprocessor. /// /// See `falcon.rst` for more details. +#[derive(Debug, Copy, Clone)] pub(crate) enum FalconSecurityModel { /// Non-Secure: runs unsigned code without privileges. - #[default] None =3D 0, /// Light-Secured (LS): Runs signed code with some privileges. /// Entry into this mode is only possible from 'Heavy-secure' mode, wh= ich verifies the code's @@ -144,16 +141,16 @@ 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 { 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 value.get() { 0 =3D> None, 2 =3D> Light, 3 =3D> Heavy, @@ -166,24 +163,22 @@ fn try_from(value: u8) -> Result { =20 /// Signing algorithm for a given firmware, used in the [`crate::regs::NV_= PFALCON2_FALCON_MOD_SEL`] /// register. It is passed to the Falcon Boot ROM (BROM) as a parameter. -#[repr(u8)] -#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] pub(crate) enum FalconModSelAlgo { /// AES. - #[expect(dead_code)] Aes =3D 0, /// RSA3K. - #[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 { type Error =3D Error; =20 - fn try_from(value: u8) -> Result { - match value { + fn try_from(value: Bounded) -> Result { + match value.get() { + 0 =3D> Ok(FalconModSelAlgo::Aes), 1 =3D> Ok(FalconModSelAlgo::Rsa3k), _ =3D> Err(EINVAL), } @@ -191,21 +186,19 @@ fn try_from(value: u8) -> Result { } =20 /// Valid values for the `size` field of the [`crate::regs::NV_PFALCON_FAL= CON_DMATRFCMD`] register. -#[repr(u8)] -#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] pub(crate) enum DmaTrfCmdSize { /// 256 bytes transfer. - #[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 { type Error =3D Error; =20 - fn try_from(value: u8) -> Result { - match value { + fn try_from(value: Bounded) -> Result { + match value.get() { 0x6 =3D> Ok(Self::Size256B), _ =3D> Err(EINVAL), } @@ -213,33 +206,24 @@ fn try_from(value: u8) -> Result { } =20 /// Currently active core on a dual falcon/riscv (Peregrine) controller. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum PeregrineCoreSelect { /// Falcon core is active. - #[default] Falcon =3D 0, /// 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 { + 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 { @@ -255,10 +239,8 @@ pub(crate) enum FalconMem { /// Defines the Framebuffer Interface (FBIF) aperture type. /// This determines the memory type for external memory access during a DM= A transfer, which is /// performed by the Falcon's Framebuffer DMA (FBDMA) engine. See falcon.r= st for more details. -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone)] pub(crate) enum FalconFbifTarget { - /// VRAM. - #[default] /// Local Framebuffer (GPU's VRAM memory). LocalFb =3D 0, /// Coherent system memory (System DRAM). @@ -266,14 +248,14 @@ 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 { 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 value.get() { 0 =3D> Self::LocalFb, 1 =3D> Self::CoherentSysmem, 2 =3D> Self::NoncoherentSysmem, @@ -285,34 +267,25 @@ fn try_from(value: u8) -> Result { } =20 /// Type of memory addresses to use. -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone)] pub(crate) enum FalconFbifMemType { /// Virtual memory addresses. - #[default] Virtual =3D 0, /// 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 { + 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 @@ -321,13 +294,10 @@ fn from(value: FalconFbifMemType) -> Self { =20 /// Trait defining the parameters of a given Falcon engine. /// -/// Each engine provides one base for `PFALCON` and `PFALCON2` registers. = The `ID` constant is used -/// to identify a given Falcon instance with register I/O methods. +/// Each engine provides one base for `PFALCON` and `PFALCON2` registers. pub(crate) trait FalconEngine: Send + Sync + RegisterBase + RegisterBase += Sized { - /// Singleton of the engine, used to identify it with register I/O met= hods. - const ID: Self; } =20 /// Represents a portion of the firmware to be loaded into a particular me= mory (e.g. IMEM or DMEM) @@ -521,8 +491,14 @@ pub(crate) fn new(dev: &device::Device, chipset: Chips= et) -> Result { =20 /// Resets DMA-related registers. pub(crate) fn dma_reset(&self, bar: &Bar0) { - regs::NV_PFALCON_FBIF_CTL::update(bar, &E::ID, |v| v.set_allow_phy= s_no_ctx(true)); - regs::NV_PFALCON_FALCON_DMACTL::default().write(bar, &E::ID); + bar.update(regs::NV_PFALCON_FBIF_CTL::of::(), |v| { + v.with_allow_phys_no_ctx(true) + }); + + bar.write( + WithBase::of::(), + regs::NV_PFALCON_FALCON_DMACTL::zeroed(), + ); } =20 /// Reset the controller, select the falcon core, and wait for memory = scrubbing to complete. @@ -531,9 +507,10 @@ pub(crate) fn reset(&self, bar: &Bar0) -> Result { self.hal.select_core(self, bar)?; self.hal.reset_wait_mem_scrubbing(bar)?; =20 - regs::NV_PFALCON_FALCON_RM::default() - .set_value(regs::NV_PMC_BOOT_0::read(bar).into()) - .write(bar, &E::ID); + bar.write( + WithBase::of::(), + regs::NV_PFALCON_FALCON_RM::from(bar.read(regs::NV_PMC_BOOT_0)= .into_raw()), + ); =20 Ok(()) } @@ -551,25 +528,27 @@ fn pio_wr_imem_slice(&self, bar: &Bar0, load_offsets:= FalconPioImemLoadTarget<'_ return Err(EINVAL); } =20 - regs::NV_PFALCON_FALCON_IMEMC::default() - .set_secure(load_offsets.secure) - .set_aincw(true) - .set_offs(load_offsets.dst_start) - .write(bar, &E::ID, Self::PIO_PORT); + bar.write( + WithBase::of::().at(Self::PIO_PORT), + regs::NV_PFALCON_FALCON_IMEMC::zeroed() + .with_secure(load_offsets.secure) + .with_aincw(true) + .with_offs(load_offsets.dst_start), + ); =20 for (n, block) in load_offsets.data.chunks(MEM_BLOCK_ALIGNMENT).en= umerate() { let n =3D u16::try_from(n)?; let tag: u16 =3D load_offsets.start_tag.checked_add(n).ok_or(E= RANGE)?; - regs::NV_PFALCON_FALCON_IMEMT::default().set_tag(tag).write( - bar, - &E::ID, - Self::PIO_PORT, + bar.write( + WithBase::of::().at(Self::PIO_PORT), + regs::NV_PFALCON_FALCON_IMEMT::zeroed().with_tag(tag), ); for word in block.chunks_exact(4) { let w =3D [word[0], word[1], word[2], word[3]]; - regs::NV_PFALCON_FALCON_IMEMD::default() - .set_data(u32::from_le_bytes(w)) - .write(bar, &E::ID, Self::PIO_PORT); + bar.write( + WithBase::of::().at(Self::PIO_PORT), + regs::NV_PFALCON_FALCON_IMEMD::zeroed().with_data(u32:= :from_le_bytes(w)), + ); } } =20 @@ -586,16 +565,19 @@ fn pio_wr_dmem_slice(&self, bar: &Bar0, load_offsets:= FalconPioDmemLoadTarget<'_ return Err(EINVAL); } =20 - regs::NV_PFALCON_FALCON_DMEMC::default() - .set_aincw(true) - .set_offs(load_offsets.dst_start) - .write(bar, &E::ID, Self::PIO_PORT); + bar.write( + WithBase::of::().at(Self::PIO_PORT), + regs::NV_PFALCON_FALCON_DMEMC::zeroed() + .with_aincw(true) + .with_offs(load_offsets.dst_start), + ); =20 for word in load_offsets.data.chunks_exact(4) { let w =3D [word[0], word[1], word[2], word[3]]; - regs::NV_PFALCON_FALCON_DMEMD::default() - .set_data(u32::from_le_bytes(w)) - .write(bar, &E::ID, Self::PIO_PORT); + bar.write( + WithBase::of::().at(Self::PIO_PORT), + regs::NV_PFALCON_FALCON_DMEMD::zeroed().with_data(u32::fro= m_le_bytes(w)), + ); } =20 Ok(()) @@ -607,11 +589,14 @@ pub(crate) fn pio_load + FalconPioLoadable>( bar: &Bar0, fw: &F, ) -> Result { - regs::NV_PFALCON_FBIF_CTL::read(bar, &E::ID) - .set_allow_phys_no_ctx(true) - .write(bar, &E::ID); + bar.update(regs::NV_PFALCON_FBIF_CTL::of::(), |v| { + v.with_allow_phys_no_ctx(true) + }); =20 - regs::NV_PFALCON_FALCON_DMACTL::default().write(bar, &E::ID); + bar.write( + WithBase::of::(), + regs::NV_PFALCON_FALCON_DMACTL::zeroed(), + ); =20 if let Some(imem_ns) =3D fw.imem_ns_load_params() { self.pio_wr_imem_slice(bar, imem_ns)?; @@ -623,9 +608,10 @@ pub(crate) fn pio_load= + FalconPioLoadable>( =20 self.hal.program_brom(self, bar, &fw.brom_params())?; =20 - regs::NV_PFALCON_FALCON_BOOTVEC::default() - .set_value(fw.boot_addr()) - .write(bar, &E::ID); + bar.write( + WithBase::of::(), + regs::NV_PFALCON_FALCON_BOOTVEC::zeroed().with_value(fw.boot_a= ddr()), + ); =20 Ok(()) } @@ -694,36 +680,42 @@ fn dma_wr( =20 // Set up the base source DMA address. =20 - regs::NV_PFALCON_FALCON_DMATRFBASE::default() - // CAST: `as u32` is used on purpose since we do want to strip= the upper bits, which - // will be written to `NV_PFALCON_FALCON_DMATRFBASE1`. - .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) - .write(bar, &E::ID); + bar.write( + WithBase::of::(), + regs::NV_PFALCON_FALCON_DMATRFBASE::zeroed().with_base( + // CAST: `as u32` is used on purpose since we do want to s= trip the upper bits, + // which will be written to `NV_PFALCON_FALCON_DMATRFBASE1= `. + (dma_start >> 8) as u32, + ), + ); + bar.write( + WithBase::of::(), + regs::NV_PFALCON_FALCON_DMATRFBASE1::zeroed().try_with_base(dm= a_start >> 40)?, + ); =20 - let cmd =3D regs::NV_PFALCON_FALCON_DMATRFCMD::default() - .set_size(DmaTrfCmdSize::Size256B) + let cmd =3D regs::NV_PFALCON_FALCON_DMATRFCMD::zeroed() + .with_size(DmaTrfCmdSize::Size256B) .with_falcon_mem(target_mem); =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) - .write(bar, &E::ID); - regs::NV_PFALCON_FALCON_DMATRFFBOFFS::default() - .set_offs(src_start + pos) - .write(bar, &E::ID); - cmd.write(bar, &E::ID); + bar.write( + WithBase::of::(), + regs::NV_PFALCON_FALCON_DMATRFMOFFS::zeroed() + .try_with_offs(load_offsets.dst_start + pos)?, + ); + bar.write( + WithBase::of::(), + regs::NV_PFALCON_FALCON_DMATRFFBOFFS::zeroed().with_offs(s= rc_start + pos), + ); + + bar.write(WithBase::of::(), cmd); =20 // Wait for the transfer to complete. // TIMEOUT: arbitrarily large value, no DMA transfer to the fa= lcon's small memories // should ever take that long. read_poll_timeout( - || Ok(regs::NV_PFALCON_FALCON_DMATRFCMD::read(bar, &E::ID)= ), + || Ok(bar.read(regs::NV_PFALCON_FALCON_DMATRFCMD::of::(= ))), |r| r.idle(), Delta::ZERO, Delta::from_secs(2), @@ -744,9 +736,9 @@ fn dma_load + FalconDma= Loadable>( let dma_obj =3D DmaObject::from_data(dev, fw.as_slice())?; =20 self.dma_reset(bar); - regs::NV_PFALCON_FBIF_TRANSCFG::update(bar, &E::ID, 0, |v| { - v.set_target(FalconFbifTarget::CoherentSysmem) - .set_mem_type(FalconFbifMemType::Physical) + bar.update(regs::NV_PFALCON_FBIF_TRANSCFG::of::().at(0), |v| { + v.with_target(FalconFbifTarget::CoherentSysmem) + .with_mem_type(FalconFbifMemType::Physical) }); =20 self.dma_wr( @@ -760,9 +752,10 @@ fn dma_load + FalconDm= aLoadable>( self.hal.program_brom(self, bar, &fw.brom_params())?; =20 // Set `BootVec` to start of non-secure code. - regs::NV_PFALCON_FALCON_BOOTVEC::default() - .set_value(fw.boot_addr()) - .write(bar, &E::ID); + bar.write( + WithBase::of::(), + regs::NV_PFALCON_FALCON_BOOTVEC::zeroed().with_value(fw.boot_a= ddr()), + ); =20 Ok(()) } @@ -771,7 +764,7 @@ fn dma_load + FalconDma= Loadable>( pub(crate) fn wait_till_halted(&self, bar: &Bar0) -> Result<()> { // TIMEOUT: arbitrarily large value, firmwares should complete in = less than 2 seconds. read_poll_timeout( - || Ok(regs::NV_PFALCON_FALCON_CPUCTL::read(bar, &E::ID)), + || Ok(bar.read(regs::NV_PFALCON_FALCON_CPUCTL::of::())), |r| r.halted(), Delta::ZERO, Delta::from_secs(2), @@ -782,13 +775,18 @@ pub(crate) fn wait_till_halted(&self, bar: &Bar0) -> = Result<()> { =20 /// Start the falcon CPU. pub(crate) fn start(&self, bar: &Bar0) -> Result<()> { - match regs::NV_PFALCON_FALCON_CPUCTL::read(bar, &E::ID).alias_en()= { - true =3D> regs::NV_PFALCON_FALCON_CPUCTL_ALIAS::default() - .set_startcpu(true) - .write(bar, &E::ID), - false =3D> regs::NV_PFALCON_FALCON_CPUCTL::default() - .set_startcpu(true) - .write(bar, &E::ID), + match bar + .read(regs::NV_PFALCON_FALCON_CPUCTL::of::()) + .alias_en() + { + true =3D> bar.write( + WithBase::of::(), + regs::NV_PFALCON_FALCON_CPUCTL_ALIAS::zeroed().with_startc= pu(true), + ), + false =3D> bar.write( + WithBase::of::(), + regs::NV_PFALCON_FALCON_CPUCTL::zeroed().with_startcpu(tru= e), + ), } =20 Ok(()) @@ -797,26 +795,30 @@ pub(crate) fn start(&self, bar: &Bar0) -> Result<()> { /// Writes values to the mailbox registers if provided. pub(crate) fn write_mailboxes(&self, bar: &Bar0, mbox0: Option, m= box1: Option) { if let Some(mbox0) =3D mbox0 { - regs::NV_PFALCON_FALCON_MAILBOX0::default() - .set_value(mbox0) - .write(bar, &E::ID); + bar.write( + WithBase::of::(), + regs::NV_PFALCON_FALCON_MAILBOX0::zeroed().with_value(mbox= 0), + ); } =20 if let Some(mbox1) =3D mbox1 { - regs::NV_PFALCON_FALCON_MAILBOX1::default() - .set_value(mbox1) - .write(bar, &E::ID); + bar.write( + WithBase::of::(), + regs::NV_PFALCON_FALCON_MAILBOX1::zeroed().with_value(mbox= 1), + ); } } =20 /// Reads the value from `mbox0` register. pub(crate) fn read_mailbox0(&self, bar: &Bar0) -> u32 { - regs::NV_PFALCON_FALCON_MAILBOX0::read(bar, &E::ID).value() + bar.read(regs::NV_PFALCON_FALCON_MAILBOX0::of::()) + .value() } =20 /// Reads the value from `mbox1` register. pub(crate) fn read_mailbox1(&self, bar: &Bar0) -> u32 { - regs::NV_PFALCON_FALCON_MAILBOX1::read(bar, &E::ID).value() + bar.read(regs::NV_PFALCON_FALCON_MAILBOX1::of::()) + .value() } =20 /// Reads values from both mailbox registers. @@ -881,8 +883,9 @@ pub(crate) fn load + Fa= lconDmaLoadable>( =20 /// Write the application version to the OS register. pub(crate) fn write_os_version(&self, bar: &Bar0, app_version: u32) { - regs::NV_PFALCON_FALCON_OS::default() - .set_value(app_version) - .write(bar, &E::ID); + bar.write( + WithBase::of::(), + regs::NV_PFALCON_FALCON_OS::zeroed().with_value(app_version), + ); } } diff --git a/drivers/gpu/nova-core/falcon/gsp.rs b/drivers/gpu/nova-core/fa= lcon/gsp.rs index 67edef3636c1..41b9fa49414c 100644 --- a/drivers/gpu/nova-core/falcon/gsp.rs +++ b/drivers/gpu/nova-core/falcon/gsp.rs @@ -1,7 +1,11 @@ // SPDX-License-Identifier: GPL-2.0 =20 use kernel::{ - io::poll::read_poll_timeout, + io::{ + poll::read_poll_timeout, + register::{RegisterBase, WithBase}, + Io, + }, prelude::*, time::Delta, // }; @@ -14,13 +18,9 @@ PFalcon2Base, PFalconBase, // }, - regs::{ - self, - macros::RegisterBase, // - }, + regs, }; =20 -/// Type specifying the `Gsp` falcon engine. Cannot be instantiated. pub(crate) struct Gsp(()); =20 impl RegisterBase for Gsp { @@ -31,23 +31,22 @@ impl RegisterBase for Gsp { const BASE: usize =3D 0x00111000; } =20 -impl FalconEngine for Gsp { - const ID: Self =3D Gsp(()); -} +impl FalconEngine for Gsp {} =20 impl Falcon { /// Clears the SWGEN0 bit in the Falcon's IRQ status clear register to /// allow GSP to signal CPU for processing new messages in message que= ue. pub(crate) fn clear_swgen0_intr(&self, bar: &Bar0) { - regs::NV_PFALCON_FALCON_IRQSCLR::default() - .set_swgen0(true) - .write(bar, &Gsp::ID); + bar.write( + WithBase::of::(), + regs::NV_PFALCON_FALCON_IRQSCLR::zeroed().with_swgen0(true), + ); } =20 /// Checks if GSP reload/resume has completed during the boot process. pub(crate) fn check_reload_completed(&self, bar: &Bar0, timeout: Delta= ) -> Result { read_poll_timeout( - || Ok(regs::NV_PGC6_BSI_SECURE_SCRATCH_14::read(bar)), + || Ok(bar.read(regs::NV_PGC6_BSI_SECURE_SCRATCH_14)), |val| val.boot_stage_3_handoff(), Delta::ZERO, timeout, diff --git a/drivers/gpu/nova-core/falcon/hal/ga102.rs b/drivers/gpu/nova-c= ore/falcon/hal/ga102.rs index 8f62df10da0a..e8c8414c90f2 100644 --- a/drivers/gpu/nova-core/falcon/hal/ga102.rs +++ b/drivers/gpu/nova-core/falcon/hal/ga102.rs @@ -4,7 +4,11 @@ =20 use kernel::{ device, - io::poll::read_poll_timeout, + io::{ + poll::read_poll_timeout, + register::{Array, WithBase}, + Io, + }, prelude::*, time::Delta, // }; @@ -25,15 +29,16 @@ use super::FalconHal; =20 fn select_core_ga102(bar: &Bar0) -> Result { - let bcr_ctrl =3D regs::NV_PRISCV_RISCV_BCR_CTRL::read(bar, &E::ID); + let bcr_ctrl =3D bar.read(regs::NV_PRISCV_RISCV_BCR_CTRL::of::()); if bcr_ctrl.core_select() !=3D PeregrineCoreSelect::Falcon { - regs::NV_PRISCV_RISCV_BCR_CTRL::default() - .set_core_select(PeregrineCoreSelect::Falcon) - .write(bar, &E::ID); + bar.write( + WithBase::of::(), + regs::NV_PRISCV_RISCV_BCR_CTRL::zeroed().with_core_select(Pere= grineCoreSelect::Falcon), + ); =20 // TIMEOUT: falcon core should take less than 10ms to report being= enabled. read_poll_timeout( - || Ok(regs::NV_PRISCV_RISCV_BCR_CTRL::read(bar, &E::ID)), + || Ok(bar.read(regs::NV_PRISCV_RISCV_BCR_CTRL::of::())), |r| r.valid(), Delta::ZERO, Delta::from_millis(10), @@ -60,34 +65,43 @@ 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 { - regs::NV_FUSE_OPT_FPF_SEC2_UCODE1_VERSION::read(bar, ucode_idx).da= ta() + let reg_fuse_version: u16 =3D if engine_id_mask & 0x0001 !=3D 0 { + bar.read(regs::NV_FUSE_OPT_FPF_SEC2_UCODE1_VERSION::at(ucode_idx)) + .data() } else if engine_id_mask & 0x0004 !=3D 0 { - regs::NV_FUSE_OPT_FPF_NVDEC_UCODE1_VERSION::read(bar, ucode_idx).d= ata() + bar.read(regs::NV_FUSE_OPT_FPF_NVDEC_UCODE1_VERSION::at(ucode_idx)) + .data() } else if engine_id_mask & 0x0400 !=3D 0 { - regs::NV_FUSE_OPT_FPF_GSP_UCODE1_VERSION::read(bar, ucode_idx).dat= a() + bar.read(regs::NV_FUSE_OPT_FPF_GSP_UCODE1_VERSION::at(ucode_idx)) + .data() } else { dev_err!(dev, "unexpected engine_id_mask {:#x}\n", 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()) } =20 fn program_brom_ga102(bar: &Bar0, params: &FalconBromPara= ms) -> Result { - regs::NV_PFALCON2_FALCON_BROM_PARAADDR::default() - .set_value(params.pkc_data_offset) - .write(bar, &E::ID, 0); - regs::NV_PFALCON2_FALCON_BROM_ENGIDMASK::default() - .set_value(u32::from(params.engine_id_mask)) - .write(bar, &E::ID); - regs::NV_PFALCON2_FALCON_BROM_CURR_UCODE_ID::default() - .set_ucode_id(params.ucode_id) - .write(bar, &E::ID); - regs::NV_PFALCON2_FALCON_MOD_SEL::default() - .set_algo(FalconModSelAlgo::Rsa3k) - .write(bar, &E::ID); + bar.write( + WithBase::of::().at(0), + regs::NV_PFALCON2_FALCON_BROM_PARAADDR::zeroed().with_value(params= .pkc_data_offset), + ); + bar.write( + WithBase::of::(), + regs::NV_PFALCON2_FALCON_BROM_ENGIDMASK::zeroed() + .with_value(u32::from(params.engine_id_mask)), + ); + bar.write( + WithBase::of::(), + regs::NV_PFALCON2_FALCON_BROM_CURR_UCODE_ID::zeroed().with_ucode_i= d(params.ucode_id), + ); + bar.write( + WithBase::of::(), + regs::NV_PFALCON2_FALCON_MOD_SEL::zeroed().with_algo(FalconModSelA= lgo::Rsa3k), + ); =20 Ok(()) } @@ -120,14 +134,14 @@ fn program_brom(&self, _falcon: &Falcon, bar: &Bar= 0, params: &FalconBromParam } =20 fn is_riscv_active(&self, bar: &Bar0) -> bool { - let cpuctl =3D regs::NV_PRISCV_RISCV_CPUCTL::read(bar, &E::ID); - cpuctl.active_stat() + bar.read(regs::NV_PRISCV_RISCV_CPUCTL::of::()) + .active_stat() } =20 fn reset_wait_mem_scrubbing(&self, bar: &Bar0) -> Result { // TIMEOUT: memory scrubbing should complete in less than 20ms. read_poll_timeout( - || Ok(regs::NV_PFALCON_FALCON_HWCFG2::read(bar, &E::ID)), + || Ok(bar.read(regs::NV_PFALCON_FALCON_HWCFG2::of::())), |r| r.mem_scrubbing_done(), Delta::ZERO, Delta::from_millis(20), @@ -136,12 +150,12 @@ fn reset_wait_mem_scrubbing(&self, bar: &Bar0) -> Res= ult { } =20 fn reset_eng(&self, bar: &Bar0) -> Result { - let _ =3D regs::NV_PFALCON_FALCON_HWCFG2::read(bar, &E::ID); + let _ =3D bar.read(regs::NV_PFALCON_FALCON_HWCFG2::of::()); =20 // According to OpenRM's `kflcnPreResetWait_GA102` documentation, = HW sometimes does not set // RESET_READY so a non-failing timeout is used. let _ =3D read_poll_timeout( - || Ok(regs::NV_PFALCON_FALCON_HWCFG2::read(bar, &E::ID)), + || Ok(bar.read(regs::NV_PFALCON_FALCON_HWCFG2::of::())), |r| r.reset_ready(), Delta::ZERO, Delta::from_micros(150), diff --git a/drivers/gpu/nova-core/falcon/hal/tu102.rs b/drivers/gpu/nova-c= ore/falcon/hal/tu102.rs index 7de6f24cc0a0..c7a90266cb44 100644 --- a/drivers/gpu/nova-core/falcon/hal/tu102.rs +++ b/drivers/gpu/nova-core/falcon/hal/tu102.rs @@ -3,7 +3,11 @@ use core::marker::PhantomData; =20 use kernel::{ - io::poll::read_poll_timeout, + io::{ + poll::read_poll_timeout, + register::WithBase, + Io, // + }, prelude::*, time::Delta, // }; @@ -49,14 +53,14 @@ fn program_brom(&self, _falcon: &Falcon, _bar: &Bar0= , _params: &FalconBromPar } =20 fn is_riscv_active(&self, bar: &Bar0) -> bool { - let cpuctl =3D regs::NV_PRISCV_RISCV_CORE_SWITCH_RISCV_STATUS::rea= d(bar, &E::ID); - cpuctl.active_stat() + bar.read(regs::NV_PRISCV_RISCV_CORE_SWITCH_RISCV_STATUS::of::()) + .active_stat() } =20 fn reset_wait_mem_scrubbing(&self, bar: &Bar0) -> Result { // TIMEOUT: memory scrubbing should complete in less than 10ms. read_poll_timeout( - || Ok(regs::NV_PFALCON_FALCON_DMACTL::read(bar, &E::ID)), + || Ok(bar.read(regs::NV_PFALCON_FALCON_DMACTL::of::())), |r| r.mem_scrubbing_done(), Delta::ZERO, Delta::from_millis(10), diff --git a/drivers/gpu/nova-core/falcon/sec2.rs b/drivers/gpu/nova-core/f= alcon/sec2.rs index b57d362e576a..91ec7d49c1f5 100644 --- a/drivers/gpu/nova-core/falcon/sec2.rs +++ b/drivers/gpu/nova-core/falcon/sec2.rs @@ -1,12 +1,11 @@ // SPDX-License-Identifier: GPL-2.0 =20 -use crate::{ - falcon::{ - FalconEngine, - PFalcon2Base, - PFalconBase, // - }, - regs::macros::RegisterBase, +use kernel::io::register::RegisterBase; + +use crate::falcon::{ + FalconEngine, + PFalcon2Base, + PFalconBase, // }; =20 /// Type specifying the `Sec2` falcon engine. Cannot be instantiated. @@ -20,6 +19,4 @@ impl RegisterBase for Sec2 { const BASE: usize =3D 0x00841000; } =20 -impl FalconEngine for Sec2 { - const ID: Self =3D Sec2(()); -} +impl FalconEngine for Sec2 {} diff --git a/drivers/gpu/nova-core/fb.rs b/drivers/gpu/nova-core/fb.rs index c62abcaed547..6b392588f766 100644 --- a/drivers/gpu/nova-core/fb.rs +++ b/drivers/gpu/nova-core/fb.rs @@ -4,6 +4,7 @@ =20 use kernel::{ device, + io::Io, prelude::*, ptr::{ Alignable, @@ -134,7 +135,10 @@ pub(crate) fn new(chipset: Chipset, bar: &Bar0, gsp_fw= : &GspFirmware) -> Result< let base =3D fb.end - NV_PRAMIN_SIZE; =20 if hal.supports_display(bar) { - match regs::NV_PDISP_VGA_WORKSPACE_BASE::read(bar).vga= _workspace_addr() { + match bar + .read(regs::NV_PDISP_VGA_WORKSPACE_BASE) + .vga_workspace_addr() + { Some(addr) =3D> { if addr < base { const VBIOS_WORKSPACE_SIZE: u64 =3D usize_= as_u64(SZ_128K); diff --git a/drivers/gpu/nova-core/fb/hal/ga100.rs b/drivers/gpu/nova-core/= fb/hal/ga100.rs index e0acc41aa7cd..1c03783cddef 100644 --- a/drivers/gpu/nova-core/fb/hal/ga100.rs +++ b/drivers/gpu/nova-core/fb/hal/ga100.rs @@ -1,6 +1,10 @@ // SPDX-License-Identifier: GPL-2.0 =20 -use kernel::prelude::*; +use kernel::{ + io::Io, + num::Bounded, + prelude::*, // +}; =20 use crate::{ driver::Bar0, @@ -13,26 +17,31 @@ struct Ga100; =20 pub(super) fn read_sysmem_flush_page_ga100(bar: &Bar0) -> u64 { - u64::from(regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR::read(bar).adr_39_08()) = << FLUSH_SYSMEM_ADDR_SHIFT - | u64::from(regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI::read(bar).adr_= 63_40()) + u64::from(bar.read(regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR).adr_39_08()) <= < FLUSH_SYSMEM_ADDR_SHIFT + | u64::from(bar.read(regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI).adr_6= 3_40()) << FLUSH_SYSMEM_ADDR_SHIFT_HI } =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) - .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 - // written to `NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI`. - .set_adr_39_08((addr >> FLUSH_SYSMEM_ADDR_SHIFT) as u32) - .write(bar); + bar.write_reg( + regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI::zeroed().with_adr_63_40( + Bounded::::from(addr) + .shr::() + .cast(), + ), + ); + + bar.write_reg( + regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR::zeroed() + // CAST: `as u32` is used on purpose since we want to strip th= e upper bits that have + // been written to `NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI`. + .with_adr_39_08((addr >> FLUSH_SYSMEM_ADDR_SHIFT) as u32), + ); } =20 pub(super) fn display_enabled_ga100(bar: &Bar0) -> bool { - !regs::ga100::NV_FUSE_STATUS_OPT_DISPLAY::read(bar).display_disabled() + !bar.read(regs::ga100::NV_FUSE_STATUS_OPT_DISPLAY) + .display_disabled() } =20 /// Shift applied to the sysmem address before it is written into diff --git a/drivers/gpu/nova-core/fb/hal/ga102.rs b/drivers/gpu/nova-core/= fb/hal/ga102.rs index 734605905031..4b9f0f74d0e7 100644 --- a/drivers/gpu/nova-core/fb/hal/ga102.rs +++ b/drivers/gpu/nova-core/fb/hal/ga102.rs @@ -1,6 +1,9 @@ // SPDX-License-Identifier: GPL-2.0 =20 -use kernel::prelude::*; +use kernel::{ + io::Io, + prelude::*, // +}; =20 use crate::{ driver::Bar0, @@ -9,7 +12,7 @@ }; =20 fn vidmem_size_ga102(bar: &Bar0) -> u64 { - regs::NV_USABLE_FB_SIZE_IN_MB::read(bar).usable_fb_size() + bar.read(regs::NV_USABLE_FB_SIZE_IN_MB).usable_fb_size() } =20 struct Ga102; diff --git a/drivers/gpu/nova-core/fb/hal/tu102.rs b/drivers/gpu/nova-core/= fb/hal/tu102.rs index eec984f4e816..281bb796e198 100644 --- a/drivers/gpu/nova-core/fb/hal/tu102.rs +++ b/drivers/gpu/nova-core/fb/hal/tu102.rs @@ -1,6 +1,9 @@ // SPDX-License-Identifier: GPL-2.0 =20 -use kernel::prelude::*; +use kernel::{ + io::Io, + prelude::*, // +}; =20 use crate::{ driver::Bar0, @@ -13,7 +16,7 @@ pub(super) const FLUSH_SYSMEM_ADDR_SHIFT: u32 =3D 8; =20 pub(super) fn read_sysmem_flush_page_gm107(bar: &Bar0) -> u64 { - u64::from(regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR::read(bar).adr_39_08()) = << FLUSH_SYSMEM_ADDR_SHIFT + u64::from(bar.read(regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR).adr_39_08()) <= < FLUSH_SYSMEM_ADDR_SHIFT } =20 pub(super) fn write_sysmem_flush_page_gm107(bar: &Bar0, addr: u64) -> Resu= lt { @@ -21,18 +24,18 @@ pub(super) fn write_sysmem_flush_page_gm107(bar: &Bar0,= addr: u64) -> Result { u32::try_from(addr >> FLUSH_SYSMEM_ADDR_SHIFT) .map_err(|_| EINVAL) .map(|addr| { - regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR::default() - .set_adr_39_08(addr) - .write(bar) + bar.write_reg(regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR::zeroed().wi= th_adr_39_08(addr)) }) } =20 pub(super) fn display_enabled_gm107(bar: &Bar0) -> bool { - !regs::gm107::NV_FUSE_STATUS_OPT_DISPLAY::read(bar).display_disabled() + !bar.read(regs::gm107::NV_FUSE_STATUS_OPT_DISPLAY) + .display_disabled() } =20 pub(super) fn vidmem_size_gp102(bar: &Bar0) -> u64 { - regs::NV_PFB_PRI_MMU_LOCAL_MEMORY_RANGE::read(bar).usable_fb_size() + bar.read(regs::NV_PFB_PRI_MMU_LOCAL_MEMORY_RANGE) + .usable_fb_size() } =20 struct Tu102; diff --git a/drivers/gpu/nova-core/firmware/fwsec/bootloader.rs b/drivers/g= pu/nova-core/firmware/fwsec/bootloader.rs index 342dba59b2f9..3b12d90d9412 100644 --- a/drivers/gpu/nova-core/firmware/fwsec/bootloader.rs +++ b/drivers/gpu/nova-core/firmware/fwsec/bootloader.rs @@ -12,6 +12,10 @@ self, Device, // }, + io::{ + register::WithBase, // + Io, + }, prelude::*, ptr::{ Alignable, @@ -33,7 +37,6 @@ Falcon, FalconBromParams, FalconDmaLoadable, - FalconEngine, FalconFbifMemType, FalconFbifTarget, FalconFirmware, @@ -288,15 +291,15 @@ pub(crate) fn run( .inspect_err(|e| dev_err!(dev, "Failed to load FWSEC firmware:= {:?}\n", e))?; =20 // Configure DMA index for the bootloader to fetch the FWSEC firmw= are from system memory. - regs::NV_PFALCON_FBIF_TRANSCFG::try_update( - bar, - &Gsp::ID, - usize::from_safe_cast(self.dmem_desc.ctx_dma), + bar.update( + regs::NV_PFALCON_FBIF_TRANSCFG::of::() + .try_at(usize::from_safe_cast(self.dmem_desc.ctx_dma)) + .ok_or(EINVAL)?, |v| { - v.set_target(FalconFbifTarget::CoherentSysmem) - .set_mem_type(FalconFbifMemType::Physical) + v.with_target(FalconFbifTarget::CoherentSysmem) + .with_mem_type(FalconFbifMemType::Physical) }, - )?; + ); =20 let (mbox0, _) =3D falcon .boot(bar, Some(0), None) diff --git a/drivers/gpu/nova-core/gfw.rs b/drivers/gpu/nova-core/gfw.rs index 9121f400046d..fb75dd10a172 100644 --- a/drivers/gpu/nova-core/gfw.rs +++ b/drivers/gpu/nova-core/gfw.rs @@ -19,7 +19,10 @@ //! Note that the devinit sequence also needs to run during suspend/resume. =20 use kernel::{ - io::poll::read_poll_timeout, + io::{ + poll::read_poll_timeout, + Io, // + }, prelude::*, time::Delta, // }; @@ -58,9 +61,11 @@ pub(crate) fn wait_gfw_boot_completion(bar: &Bar0) -> Re= sult { Ok( // Check that FWSEC has lowered its protection level befor= e reading the GFW_BOOT // status. - regs::NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_PRIV_LEVEL_MASK:= :read(bar) + bar.read(regs::NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_PRIV_LE= VEL_MASK) .read_protection_level0() - && regs::NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_0_GFW_BOO= T::read(bar).completed(), + && bar + .read(regs::NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_0_= GFW_BOOT) + .completed(), ) }, |&gfw_booted| gfw_booted, diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs index 8579d632e717..bb1c6bf88657 100644 --- a/drivers/gpu/nova-core/gpu.rs +++ b/drivers/gpu/nova-core/gpu.rs @@ -4,6 +4,8 @@ device, devres::Devres, fmt, + io::Io, + num::Bounded, pci, prelude::*, sync::Arc, // @@ -129,24 +131,19 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Res= ult { } =20 /// Enum representation of the GPU generation. -/// -/// TODO: remove the `Default` trait implementation, and the `#[default]` -/// attribute, once the register!() macro (which creates Architecture item= s) no -/// longer requires it for read-only fields. -#[derive(fmt::Debug, Default, Copy, Clone)] +#[derive(fmt::Debug, Copy, Clone)] #[repr(u8)] pub(crate) enum Architecture { - #[default] Turing =3D 0x16, Ampere =3D 0x17, Ada =3D 0x19, } =20 -impl TryFrom for Architecture { +impl TryFrom> for Architecture { type Error =3D Error; =20 - fn try_from(value: u8) -> Result { - match value { + fn try_from(value: Bounded) -> Result { + match u8::from(value) { 0x16 =3D> Ok(Self::Turing), 0x17 =3D> Ok(Self::Ampere), 0x19 =3D> Ok(Self::Ada), @@ -155,23 +152,26 @@ fn try_from(value: u8) -> Result { } } =20 -impl From for u8 { +impl From for Bounded { fn from(value: Architecture) -> Self { - // CAST: `Architecture` is `repr(u8)`, so this cast is always loss= less. - value as u8 + match value { + Architecture::Turing =3D> Bounded::::new::<0x16>().cast= (), + Architecture::Ampere =3D> Bounded::::new::<0x17>().cast= (), + Architecture::Ada =3D> Bounded::::new::<0x19>().cast(), + } } } =20 pub(crate) struct Revision { - major: u8, - minor: u8, + major: Bounded, + minor: Bounded, } =20 impl From for Revision { fn from(boot0: regs::NV_PMC_BOOT_42) -> Self { Self { - major: boot0.major_revision(), - minor: boot0.minor_revision(), + major: boot0.major_revision().cast(), + minor: boot0.minor_revision().cast(), } } } @@ -208,13 +208,13 @@ fn new(dev: &device::Device, bar: &Bar0) -> Result { // from an earlier (pre-Fermi) era, and then using boot42 to p= recisely identify the GPU. // Somewhere in the Rubin timeframe, boot0 will no longer have= space to add new GPU IDs. =20 - let boot0 =3D regs::NV_PMC_BOOT_0::read(bar); + let boot0 =3D bar.read(regs::NV_PMC_BOOT_0); =20 if boot0.is_older_than_fermi() { return Err(ENODEV); } =20 - let boot42 =3D regs::NV_PMC_BOOT_42::read(bar); + let boot42 =3D bar.read(regs::NV_PMC_BOOT_42); Spec::try_from(boot42).inspect_err(|_| { dev_err!(dev, "Unsupported chipset: {}\n", boot42); }) diff --git a/drivers/gpu/nova-core/gsp/boot.rs b/drivers/gpu/nova-core/gsp/= boot.rs index 9a00ddb922ac..d9d999519183 100644 --- a/drivers/gpu/nova-core/gsp/boot.rs +++ b/drivers/gpu/nova-core/gsp/boot.rs @@ -5,6 +5,7 @@ dma::CoherentAllocation, dma_write, io::poll::read_poll_timeout, + io::Io, pci, prelude::*, time::Delta, // @@ -57,7 +58,7 @@ fn run_fwsec_frts( ) -> Result<()> { // Check that the WPR2 region does not already exists - if it does= , we cannot run // FWSEC-FRTS until the GPU is reset. - if regs::NV_PFB_PRI_MMU_WPR2_ADDR_HI::read(bar).higher_bound() != =3D 0 { + if bar.read(regs::NV_PFB_PRI_MMU_WPR2_ADDR_HI).higher_bound() !=3D= 0 { dev_err!( dev, "WPR2 region already exists - GPU needs to be reset to pro= ceed\n" @@ -87,7 +88,9 @@ fn run_fwsec_frts( } =20 // SCRATCH_E contains the error code for FWSEC-FRTS. - let frts_status =3D regs::NV_PBUS_SW_SCRATCH_0E_FRTS_ERR::read(bar= ).frts_err_code(); + let frts_status =3D bar + .read(regs::NV_PBUS_SW_SCRATCH_0E_FRTS_ERR) + .frts_err_code(); if frts_status !=3D 0 { dev_err!( dev, @@ -100,8 +103,8 @@ fn run_fwsec_frts( =20 // Check that the WPR2 region has been created as we requested. let (wpr2_lo, wpr2_hi) =3D ( - regs::NV_PFB_PRI_MMU_WPR2_ADDR_LO::read(bar).lower_bound(), - regs::NV_PFB_PRI_MMU_WPR2_ADDR_HI::read(bar).higher_bound(), + bar.read(regs::NV_PFB_PRI_MMU_WPR2_ADDR_LO).lower_bound(), + bar.read(regs::NV_PFB_PRI_MMU_WPR2_ADDR_HI).higher_bound(), ); =20 match (wpr2_lo, wpr2_hi) { diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/= cmdq.rs index 87dbbd6d1be9..fe723e400166 100644 --- a/drivers/gpu/nova-core/gsp/cmdq.rs +++ b/drivers/gpu/nova-core/gsp/cmdq.rs @@ -15,7 +15,10 @@ DmaAddress, // }, dma_write, - io::poll::read_poll_timeout, + io::{ + poll::read_poll_timeout, + Io, // + }, prelude::*, sync::aref::ARef, time::Delta, @@ -488,9 +491,7 @@ fn calculate_checksum>(it: T) = -> u32 { =20 /// Notifies the GSP that we have updated the command queue pointers. fn notify_gsp(bar: &Bar0) { - regs::NV_PGSP_QUEUE_HEAD::default() - .set_address(0) - .write(bar); + bar.write_reg(regs::NV_PGSP_QUEUE_HEAD::zeroed().with_address(0u32= )); } =20 /// Sends `command` to the GSP. diff --git a/drivers/gpu/nova-core/regs.rs b/drivers/gpu/nova-core/regs.rs index 53f412f0ca32..c3905879f5b6 100644 --- a/drivers/gpu/nova-core/regs.rs +++ b/drivers/gpu/nova-core/regs.rs @@ -1,13 +1,10 @@ // SPDX-License-Identifier: GPL-2.0 =20 -// Required to retain the original register names used by OpenRM, which ar= e all capital snake case -// but are mapped to types. -#![allow(non_camel_case_types)] - -#[macro_use] -pub(crate) mod macros; - use kernel::{ + io::{ + register::WithBase, + Io, // + }, prelude::*, time, // }; @@ -35,20 +32,64 @@ num::FromSafeCast, }; =20 +// All nova-core registers are 32-bit and `pub(crate)`. Wrap the `register= !` macro to avoid +// repeating this information for every register. +macro_rules! nv_reg { + ( + $( + $(#[$attr:meta])* $name:ident $([ $size:expr $(, stride =3D $s= tride:expr)? ])? + $(@ $offset:literal)? + $(@ $base:ident + $base_offset:literal)? + $(=3D> $alias:ident $(+ $alias_offset:ident)? $([$alias_id= x:expr])? )? + $(, $comment:literal)? { $($fields:tt)* } + )* + )=3D> { + $( + ::kernel::io::register!( + @reg $(#[$attr])* pub(crate) $name(u32) $([$size $(, stride = =3D $stride)?])? + $(@ $offset)? + $(@ $base + $base_offset)? + $(=3D> $alias $(+ $alias_offset)? $([$alias_idx])? )? + $(, $comment)? { $($fields)* } + ); + )* + }; +} + // 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"; -}); +nv_reg! { + /// Basic revision information about the GPU. + NV_PMC_BOOT_0 @ 0x00000000 { + /// Minor revision of the chip. + 3:0 minor_revision; + /// Major revision of the chip. + 7:4 major_revision; + /// Meta-variable `newbase` repeats 0 times, but `offset` repeats = 1 time. + 8:8 architecture_1; + /// Implementation version of the architecture. + 23:20 implementation; + /// Lower bits of the architecture. + 28:24 architecture_0; + } + + /// Extended architecture information. + NV_PMC_BOOT_42 @ 0x00000a00 { + /// Minor revision of the chip. + 15:12 minor_revision; + /// Major revision of the chip. + 19:16 major_revision; + /// Implementation version of the architecture. + 23:20 implementation; + /// Architecture value. + 29:24 architecture ?=3D> Architecture; + } +} =20 impl NV_PMC_BOOT_0 { pub(crate) fn is_older_than_fermi(self) -> bool { // From https://github.com/NVIDIA/open-gpu-doc/tree/master/manuals= : - const NV_PMC_BOOT_0_ARCHITECTURE_GF100: u8 =3D 0xc; + const NV_PMC_BOOT_0_ARCHITECTURE_GF100: u32 =3D 0xc; =20 // Older chips left arch1 zeroed out. That, combined with an arch0= value that is less than // GF100, means "older than Fermi". @@ -56,13 +97,6 @@ pub(crate) fn is_older_than_fermi(self) -> bool { } } =20 -register!(NV_PMC_BOOT_42 @ 0x00000a00, "Extended architecture information"= { - 15:12 minor_revision as u8, "Minor revision of the chip"; - 19:16 major_revision as u8, "Major revision of the chip"; - 23:20 implementation as u8, "Implementation version of the architect= ure"; - 29:24 architecture as u8 ?=3D> Architecture, "Architecture value"; -}); - impl NV_PMC_BOOT_42 { /// Combines `architecture` and `implementation` to obtain a code uniq= ue to the chipset. pub(crate) fn chipset(self) -> Result { @@ -76,8 +110,8 @@ pub(crate) fn chipset(self) -> Result { =20 /// Returns the raw architecture value from the register. fn architecture_raw(self) -> u8 { - ((self.0 >> Self::ARCHITECTURE_RANGE.start()) & ((1 << Self::ARCHI= TECTURE_RANGE.len()) - 1)) - as u8 + ((self.inner >> Self::ARCHITECTURE_RANGE.start()) + & ((1 << Self::ARCHITECTURE_RANGE.len()) - 1)) as u8 } } =20 @@ -86,7 +120,7 @@ fn fmt(&self, f: &mut kernel::fmt::Formatter<'_>) -> ker= nel::fmt::Result { write!( f, "boot42 =3D 0x{:08x} (architecture 0x{:x}, implementation 0x{:= x})", - self.0, + self.inner, self.architecture_raw(), self.implementation() ) @@ -95,35 +129,46 @@ fn fmt(&self, f: &mut kernel::fmt::Formatter<'_>) -> k= ernel::fmt::Result { =20 // PBUS =20 -register!(NV_PBUS_SW_SCRATCH @ 0x00001400[64] {}); +nv_reg! { + NV_PBUS_SW_SCRATCH[64] @ 0x00001400 {} =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; -}); + /// Scratch register 0xe used as FRTS firmware error code. + NV_PBUS_SW_SCRATCH_0E_FRTS_ERR =3D> NV_PBUS_SW_SCRATCH[0xe] { + 31:16 frts_err_code; + } +} =20 // PFB =20 -// The following two registers together hold the physical system memory ad= dress that is used by the -// GPU to perform sysmembar operations (see `fb::SysmemFlush`). +nv_reg! { + /// Low bits of the physical system memory address used by the GPU to = perform sysmembar + /// operations (see [`crate::fb::SysmemFlush`]). + NV_PFB_NISO_FLUSH_SYSMEM_ADDR @ 0x00100c10 { + 31:0 adr_39_08; + } =20 -register!(NV_PFB_NISO_FLUSH_SYSMEM_ADDR @ 0x00100c10 { - 31:0 adr_39_08 as u32; -}); + /// High bits of the physical system memory address used by the GPU to= perform sysmembar + /// operations (see [`crate::fb::SysmemFlush`]). + NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI @ 0x00100c40 { + 23:0 adr_63_40; + } =20 -register!(NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI @ 0x00100c40 { - 23:0 adr_63_40 as u32; -}); + NV_PFB_PRI_MMU_LOCAL_MEMORY_RANGE @ 0x00100ce0 { + 3:0 lower_scale; + 9:4 lower_mag; + 30:30 ecc_mode_enabled =3D> bool; + } =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; -}); + NV_PFB_PRI_MMU_WPR2_ADDR_LO @ 0x001fa824 { + /// Bits 12..40 of the lower (inclusive) bound of the WPR2 region. + 31:4 lo_val; + } =20 -register!(NV_PGSP_QUEUE_HEAD @ 0x00110c00 { - 31:0 address as u32; -}); + NV_PFB_PRI_MMU_WPR2_ADDR_HI @ 0x001fa828 { + /// Bits 12..40 of the higher (exclusive) bound of the WPR2 region. + 31:4 hi_val; + } +} =20 impl NV_PFB_PRI_MMU_LOCAL_MEMORY_RANGE { /// Returns the usable framebuffer size, in bytes. @@ -140,10 +185,6 @@ 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"; -}); - impl NV_PFB_PRI_MMU_WPR2_ADDR_LO { /// Returns the lower (inclusive) bound of the WPR2 region. pub(crate) fn lower_bound(self) -> u64 { @@ -151,10 +192,6 @@ 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"; -}); - impl NV_PFB_PRI_MMU_WPR2_ADDR_HI { /// Returns the higher (exclusive) bound of the WPR2 region. /// @@ -164,6 +201,14 @@ pub(crate) fn higher_bound(self) -> u64 { } } =20 +// PGSP + +nv_reg! { + NV_PGSP_QUEUE_HEAD @ 0x00110c00 { + 31:0 address; + } +} + // PGC6 register space. // // `GC6` is a GPU low-power state where VRAM is in self-refresh and the GP= U is powered down (except @@ -173,29 +218,30 @@ pub(crate) fn higher_bound(self) -> u64 { // These scratch registers remain powered on even in a low-power state and= have a designated group // number. =20 -// Boot Sequence Interface (BSI) register used to determine -// if GSP reload/resume has completed during the boot process. -register!(NV_PGC6_BSI_SECURE_SCRATCH_14 @ 0x001180f8 { - 26:26 boot_stage_3_handoff as bool; -}); - -// Privilege level mask register. It dictates whether the host CPU has pri= vilege to access the -// `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"; -}); - -// 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_PGC6_AON_SECURE_SCRATCH_GROUP_05 @ 0x00118234[1] {}); - -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= )"; +nv_reg! { + /// Boot Sequence Interface (BSI) register used to determine + /// if GSP reload/resume has completed during the boot process. + NV_PGC6_BSI_SECURE_SCRATCH_14 @ 0x001180f8 { + 26:26 boot_stage_3_handoff =3D> bool; } -); + + /// Privilege level mask register. It dictates whether the host CPU ha= s privilege to access the + /// `PGC6_AON_SECURE_SCRATCH_GROUP_05` register (which it needs to rea= d GFW_BOOT). + NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_PRIV_LEVEL_MASK @ 0x00118128 { + /// Set after FWSEC lowers its protection level. + 0:0 read_protection_level0 =3D> bool; + } + + /// OpenRM defines this as a register array, but doesn't specify its s= ize and only uses its + /// first element. Be conservative until we know the actual size or ne= ed to use more registers. + NV_PGC6_AON_SECURE_SCRATCH_GROUP_05[1] @ 0x00118234 {} + + /// Scratch group 05 register 0 used as GFW boot progress indicator. + NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_0_GFW_BOOT =3D> NV_PGC6_AON_SECURE= _SCRATCH_GROUP_05[0] { + /// Progress of GFW boot (0xff means completed). + 7:0 progress; + } +} =20 impl NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_0_GFW_BOOT { /// Returns `true` if GFW boot is completed. @@ -204,16 +250,17 @@ pub(crate) fn completed(self) -> bool { } } =20 -register!(NV_PGC6_AON_SECURE_SCRATCH_GROUP_42 @ 0x001183a4 { - 31:0 value as u32; -}); - -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"; +nv_reg! { + NV_PGC6_AON_SECURE_SCRATCH_GROUP_42 @ 0x001183a4 { + 31:0 value; } -); + + /// Scratch group 42 register used as framebuffer size. + NV_USABLE_FB_SIZE_IN_MB =3D> NV_PGC6_AON_SECURE_SCRATCH_GROUP_42 { + /// Usable framebuffer size, in megabytes. + 31:0 value; + } +} =20 impl NV_USABLE_FB_SIZE_IN_MB { /// Returns the usable framebuffer size, in bytes. @@ -224,10 +271,14 @@ pub(crate) fn usable_fb_size(self) -> u64 { =20 // 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"; -}); +nv_reg! { + NV_PDISP_VGA_WORKSPACE_BASE @ 0x00625f04 { + /// Set if the `addr` field is valid. + 3:3 status_valid =3D> bool; + /// VGA workspace base address divided by 0x10000. + 31:8 addr; + } +} =20 impl NV_PDISP_VGA_WORKSPACE_BASE { /// Returns the base address of the VGA workspace, or `None` if none e= xists. @@ -244,73 +295,162 @@ pub(crate) fn vga_workspace_addr(self) -> Option { =20 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; -}); +nv_reg! { + NV_FUSE_OPT_FPF_NVDEC_UCODE1_VERSION[NV_FUSE_OPT_FPF_SIZE] @ 0x0082410= 0 { + 15:0 data; + } =20 -register!(NV_FUSE_OPT_FPF_SEC2_UCODE1_VERSION @ 0x00824140[NV_FUSE_OPT_FPF= _SIZE] { - 15:0 data as u16; -}); + NV_FUSE_OPT_FPF_SEC2_UCODE1_VERSION[NV_FUSE_OPT_FPF_SIZE] @ 0x00824140= { + 15:0 data; + } =20 -register!(NV_FUSE_OPT_FPF_GSP_UCODE1_VERSION @ 0x008241c0[NV_FUSE_OPT_FPF_= SIZE] { - 15:0 data as u16; -}); - -// PFALCON - -register!(NV_PFALCON_FALCON_IRQSCLR @ PFalconBase[0x00000004] { - 4:4 halt as bool; - 6:6 swgen0 as bool; -}); - -register!(NV_PFALCON_FALCON_MAILBOX0 @ PFalconBase[0x00000040] { - 31:0 value as u32; -}); - -register!(NV_PFALCON_FALCON_MAILBOX1 @ PFalconBase[0x00000044] { - 31:0 value as u32; -}); - -// Used to store version information about the firmware running -// on the Falcon processor. -register!(NV_PFALCON_FALCON_OS @ PFalconBase[0x00000080] { - 31:0 value as u32; -}); - -register!(NV_PFALCON_FALCON_RM @ PFalconBase[0x00000084] { - 31:0 value as u32; -}); - -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+)"; -}); - -impl NV_PFALCON_FALCON_HWCFG2 { - /// Returns `true` if memory scrubbing is completed. - pub(crate) fn mem_scrubbing_done(self) -> bool { - !self.mem_scrubbing() + NV_FUSE_OPT_FPF_GSP_UCODE1_VERSION[NV_FUSE_OPT_FPF_SIZE] @ 0x008241c0 { + 15:0 data; } } =20 -register!(NV_PFALCON_FALCON_CPUCTL @ PFalconBase[0x00000100] { - 1:1 startcpu as bool; - 4:4 halted as bool; - 6:6 alias_en as bool; -}); +// PFALCON =20 -register!(NV_PFALCON_FALCON_BOOTVEC @ PFalconBase[0x00000104] { - 31:0 value as u32; -}); +nv_reg! { + NV_PFALCON_FALCON_IRQSCLR @ PFalconBase + 0x00000004 { + 4:4 halt =3D> bool; + 6:6 swgen0 =3D> bool; + } =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; -}); + NV_PFALCON_FALCON_MAILBOX0 @ PFalconBase + 0x00000040 { + 31:0 value =3D> u32; + } + + NV_PFALCON_FALCON_MAILBOX1 @ PFalconBase + 0x00000044 { + 31:0 value =3D> u32; + } + + /// Used to store version information about the firmware running + /// on the Falcon processor. + NV_PFALCON_FALCON_OS @ PFalconBase + 0x00000080 { + 31:0 value =3D> u32; + } + + NV_PFALCON_FALCON_RM @ PFalconBase + 0x00000084 { + 31:0 value =3D> u32; + } + + NV_PFALCON_FALCON_HWCFG2 @ PFalconBase + 0x000000f4 { + 10:10 riscv =3D> bool; + /// Set to 0 after memory scrubbing is completed. + 12:12 mem_scrubbing =3D> bool; + /// Signal indicating that reset is completed (GA102+). + 31:31 reset_ready =3D> bool; + } + + NV_PFALCON_FALCON_CPUCTL @ PFalconBase + 0x00000100 { + 1:1 startcpu =3D> bool; + 4:4 halted =3D> bool; + 6:6 alias_en =3D> bool; + } + + NV_PFALCON_FALCON_BOOTVEC @ PFalconBase + 0x00000104 { + 31:0 value =3D> u32; + } + + NV_PFALCON_FALCON_DMACTL @ PFalconBase + 0x0000010c { + 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; + } + + NV_PFALCON_FALCON_DMATRFBASE @ PFalconBase + 0x00000110 { + 31:0 base =3D> u32; + } + + NV_PFALCON_FALCON_DMATRFMOFFS @ PFalconBase + 0x00000114 { + 23:0 offs; + } + + NV_PFALCON_FALCON_DMATRFCMD @ PFalconBase + 0x00000118 { + 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; + } + + NV_PFALCON_FALCON_DMATRFFBOFFS @ PFalconBase + 0x0000011c { + 31:0 offs =3D> u32; + } + + NV_PFALCON_FALCON_DMATRFBASE1 @ PFalconBase + 0x00000128 { + 8:0 base; + } + + NV_PFALCON_FALCON_HWCFG1 @ PFalconBase + 0x0000012c { + /// Core revision. + 3:0 core_rev ?=3D> FalconCoreRev; + /// Security model. + 5:4 security_model ?=3D> FalconSecurityModel; + /// Core revision subversion. + 7:6 core_rev_subversion =3D> FalconCoreRevSubversion; + } + + NV_PFALCON_FALCON_CPUCTL_ALIAS @ PFalconBase + 0x00000130 { + 1:1 startcpu =3D> bool; + } + + /// IMEM access control register. Up to 4 ports are available for IMEM= access. + NV_PFALCON_FALCON_IMEMC[4, stride =3D 16] @ PFalconBase + 0x00000180 { + /// IMEM block and word offset. + 15:0 offs; + /// Auto-increment on write. + 24:24 aincw =3D> bool; + /// Access secure IMEM. + 28:28 secure =3D> bool; + } + + /// IMEM data register. Reading/writing this register accesses IMEM at= the address + /// specified by the corresponding IMEMC register. + NV_PFALCON_FALCON_IMEMD[4, stride =3D 16] @ PFalconBase + 0x00000184 { + 31:0 data; + } + + /// IMEM tag register. Used to set the tag for the current IMEM block. + NV_PFALCON_FALCON_IMEMT[4, stride =3D 16] @ PFalconBase + 0x00000188 { + 15:0 tag; + } + + /// DMEM access control register. Up to 8 ports are available for DMEM= access. + NV_PFALCON_FALCON_DMEMC[8, stride =3D 8] @ PFalconBase + 0x000001c0 { + /// DMEM block and word offset. + 15:0 offs; + /// Auto-increment on write. + 24:24 aincw =3D> bool; + } + + /// DMEM data register. Reading/writing this register accesses DMEM at= the address + /// specified by the corresponding DMEMC register. + NV_PFALCON_FALCON_DMEMD[8, stride =3D 8] @ PFalconBase + 0x000001c4 { + 31:0 data; + } + + /// Actually known as `NV_PSEC_FALCON_ENGINE` and `NV_PGSP_FALCON_ENGI= NE` depending on the + /// falcon instance. + NV_PFALCON_FALCON_ENGINE @ PFalconBase + 0x000003c0 { + 0:0 reset =3D> bool; + } + + NV_PFALCON_FBIF_TRANSCFG[8] @ PFalconBase + 0x00000600 { + 1:0 target ?=3D> FalconFbifTarget; + 2:2 mem_type =3D> FalconFbifMemType; + } + + NV_PFALCON_FBIF_CTL @ PFalconBase + 0x00000624 { + 7:7 allow_phys_no_ctx =3D> bool; + } +} =20 impl NV_PFALCON_FALCON_DMACTL { /// Returns `true` if memory scrubbing is completed. @@ -319,147 +459,81 @@ pub(crate) fn mem_scrubbing_done(self) -> bool { } } =20 -register!(NV_PFALCON_FALCON_DMATRFBASE @ PFalconBase[0x00000110] { - 31:0 base as u32; -}); - -register!(NV_PFALCON_FALCON_DMATRFMOFFS @ PFalconBase[0x00000114] { - 23:0 offs as u32; -}); - -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; -}); - impl NV_PFALCON_FALCON_DMATRFCMD { /// Programs the `imem` and `sec` fields for the given FalconMem pub(crate) fn with_falcon_mem(self, mem: FalconMem) -> Self { - self.set_imem(mem !=3D FalconMem::Dmem) - .set_sec(if mem =3D=3D FalconMem::ImemSecure { 1 } else { 0 }) + let this =3D self.with_imem(mem !=3D FalconMem::Dmem); + + match mem { + FalconMem::ImemSecure =3D> this.with_const_sec::<1>(), + _ =3D> this.with_const_sec::<0>(), + } } } =20 -register!(NV_PFALCON_FALCON_DMATRFFBOFFS @ PFalconBase[0x0000011c] { - 31:0 offs as u32; -}); - -register!(NV_PFALCON_FALCON_DMATRFBASE1 @ PFalconBase[0x00000128] { - 8:0 base as u16; -}); - -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"; -}); - -register!(NV_PFALCON_FALCON_CPUCTL_ALIAS @ PFalconBase[0x00000130] { - 1:1 startcpu as bool; -}); - -// IMEM access control register. Up to 4 ports are available for IMEM acce= ss. -register!(NV_PFALCON_FALCON_IMEMC @ PFalconBase[0x00000180[4; 16]] { - 15:0 offs as u16, "IMEM block and word offset"; - 24:24 aincw as bool, "Auto-increment on write"; - 28:28 secure as bool, "Access secure IMEM"; -}); - -// IMEM data register. Reading/writing this register accesses IMEM at the = address -// specified by the corresponding IMEMC register. -register!(NV_PFALCON_FALCON_IMEMD @ PFalconBase[0x00000184[4; 16]] { - 31:0 data as u32; -}); - -// IMEM tag register. Used to set the tag for the current IMEM block. -register!(NV_PFALCON_FALCON_IMEMT @ PFalconBase[0x00000188[4; 16]] { - 15:0 tag as u16; -}); - -// DMEM access control register. Up to 8 ports are available for DMEM acce= ss. -register!(NV_PFALCON_FALCON_DMEMC @ PFalconBase[0x000001c0[8; 8]] { - 15:0 offs as u16, "DMEM block and word offset"; - 24:24 aincw as bool, "Auto-increment on write"; -}); - -// DMEM data register. Reading/writing this register accesses DMEM at the = address -// specified by the corresponding DMEMC register. -register!(NV_PFALCON_FALCON_DMEMD @ PFalconBase[0x000001c4[8; 8]] { - 31:0 data as u32; -}); - -// 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; -}); - impl NV_PFALCON_FALCON_ENGINE { /// Resets the falcon pub(crate) fn reset_engine(bar: &Bar0) { - Self::read(bar, &E::ID).set_reset(true).write(bar, &E::ID); + bar.update(Self::of::(), |r| r.with_reset(true)); =20 // TIMEOUT: falcon engine should not take more than 10us to reset. time::delay::fsleep(time::Delta::from_micros(10)); =20 - Self::read(bar, &E::ID).set_reset(false).write(bar, &E::ID); + bar.update(Self::of::(), |r| r.with_reset(false)); } } =20 -register!(NV_PFALCON_FBIF_TRANSCFG @ PFalconBase[0x00000600[8]] { - 1:0 target as u8 ?=3D> FalconFbifTarget; - 2:2 mem_type as bool =3D> FalconFbifMemType; -}); - -register!(NV_PFALCON_FBIF_CTL @ PFalconBase[0x00000624] { - 7:7 allow_phys_no_ctx as bool; -}); +impl NV_PFALCON_FALCON_HWCFG2 { + /// Returns `true` if memory scrubbing is completed. + pub(crate) fn mem_scrubbing_done(self) -> bool { + !self.mem_scrubbing() + } +} =20 /* PFALCON2 */ =20 -register!(NV_PFALCON2_FALCON_MOD_SEL @ PFalcon2Base[0x00000180] { - 7:0 algo as u8 ?=3D> FalconModSelAlgo; -}); +nv_reg! { + NV_PFALCON2_FALCON_MOD_SEL @ PFalcon2Base + 0x00000180 { + 7:0 algo ?=3D> FalconModSelAlgo; + } =20 -register!(NV_PFALCON2_FALCON_BROM_CURR_UCODE_ID @ PFalcon2Base[0x00000198]= { - 7:0 ucode_id as u8; -}); + NV_PFALCON2_FALCON_BROM_CURR_UCODE_ID @ PFalcon2Base + 0x00000198 { + 7:0 ucode_id =3D> u8; + } =20 -register!(NV_PFALCON2_FALCON_BROM_ENGIDMASK @ PFalcon2Base[0x0000019c] { - 31:0 value as u32; -}); + NV_PFALCON2_FALCON_BROM_ENGIDMASK @ PFalcon2Base + 0x0000019c { + 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; -}); + /// OpenRM defines this as a register array, but doesn't specify its s= ize and only uses its + /// first element. Be conservative until we know the actual size or ne= ed to use more registers. + NV_PFALCON2_FALCON_BROM_PARAADDR[1] @ PFalcon2Base + 0x00000210 { + 31:0 value =3D> u32; + } +} =20 // PRISCV =20 -// RISC-V status register for debug (Turing and GA100 only). -// Reflects current RISC-V core status. -register!(NV_PRISCV_RISCV_CORE_SWITCH_RISCV_STATUS @ PFalcon2Base[0x000002= 40] { - 0:0 active_stat as bool, "RISC-V core active/inactive status"; -}); - // GA102 and later -register!(NV_PRISCV_RISCV_CPUCTL @ PFalcon2Base[0x00000388] { - 0:0 halted as bool; - 7:7 active_stat as bool; -}); +nv_reg! { + // RISC-V status register for debug (Turing and GA100 only). + // Reflects current RISC-V core status. + NV_PRISCV_RISCV_CORE_SWITCH_RISCV_STATUS @ PFalcon2Base + 0x00000240 { + // RISC-V core active/inactive status. + 0:0 active_stat =3D> bool; + } =20 -register!(NV_PRISCV_RISCV_BCR_CTRL @ PFalcon2Base[0x00000668] { - 0:0 valid as bool; - 4:4 core_select as bool =3D> PeregrineCoreSelect; - 8:8 br_fetch as bool; -}); + NV_PRISCV_RISCV_CPUCTL @ PFalcon2Base + 0x00000388 { + 0:0 halted =3D> bool; + 7:7 active_stat =3D> bool; + } + + NV_PRISCV_RISCV_BCR_CTRL @ PFalconBase + 0x00001668 { + 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 // only be used in HAL modules. @@ -467,15 +541,19 @@ pub(crate) fn reset_engine(bar: &Bar= 0) { pub(crate) mod gm107 { // FUSE =20 - register!(NV_FUSE_STATUS_OPT_DISPLAY @ 0x00021c04 { - 0:0 display_disabled as bool; - }); + nv_reg! { + NV_FUSE_STATUS_OPT_DISPLAY @ 0x00021c04 { + 0:0 display_disabled =3D> bool; + } + } } =20 pub(crate) mod ga100 { // FUSE =20 - register!(NV_FUSE_STATUS_OPT_DISPLAY @ 0x00820c04 { - 0:0 display_disabled as bool; - }); + nv_reg! { + NV_FUSE_STATUS_OPT_DISPLAY @ 0x00820c04 { + 0:0 display_disabled =3D> bool; + } + } } diff --git a/drivers/gpu/nova-core/regs/macros.rs b/drivers/gpu/nova-core/r= egs/macros.rs deleted file mode 100644 index ed624be1f39b..000000000000 --- a/drivers/gpu/nova-core/regs/macros.rs +++ /dev/null @@ -1,739 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 - -//! `register!` macro to define register layout and accessors. -//! -//! A single register typically includes several fields, which are accesse= d through a combination -//! of bit-shift and mask operations that introduce a class of potential m= istakes, notably because -//! not all possible field values are necessarily valid. -//! -//! The `register!` macro in this module provides an intuitive and readabl= e syntax for defining a -//! dedicated type for each register. Each such type comes with its own fi= eld accessors that can -//! return an error if a field's value is invalid. Please look at the [`bi= tfield`] macro for the -//! complete syntax of fields definitions. - -/// Trait providing a base address to be added to the offset of a relative= register to obtain -/// its actual offset. -/// -/// The `T` generic argument is used to distinguish which base to use, in = case a type provides -/// several bases. It is given to the `register!` macro to restrict the us= e of the register to -/// implementors of this particular variant. -pub(crate) trait RegisterBase { - const BASE: usize; -} - -/// Defines a dedicated type for a register with an absolute offset, inclu= ding getter and setter -/// methods for its fields and methods to read and write it from an `Io` r= egion. -/// -/// Example: -/// -/// ```no_run -/// register!(BOOT_0 @ 0x00000100, "Basic revision information about the G= PU" { -/// 3:0 minor_revision as u8, "Minor revision of the chip"; -/// 7:4 major_revision as u8, "Major revision of the chip"; -/// 28:20 chipset as u32 ?=3D> Chipset, "Chipset model"; -/// }); -/// ``` -/// -/// This defines a `BOOT_0` type which can be read or written from offset = `0x100` of an `Io` -/// region. It is composed of 3 fields, for instance `minor_revision` is m= ade of the 4 least -/// significant bits of the register. Each field can be accessed and modif= ied using accessor -/// methods: -/// -/// ```no_run -/// // Read from the register's defined offset (0x100). -/// let boot0 =3D BOOT_0::read(&bar); -/// pr_info!("chip revision: {}.{}", boot0.major_revision(), boot0.minor_r= evision()); -/// -/// // `Chipset::try_from` is called with the value of the `chipset` field= and returns an -/// // error if it is invalid. -/// let chipset =3D boot0.chipset()?; -/// -/// // Update some fields and write the value back. -/// boot0.set_major_revision(3).set_minor_revision(10).write(&bar); -/// -/// // Or, just read and update the register in a single step: -/// BOOT_0::update(&bar, |r| r.set_major_revision(3).set_minor_revision(10= )); -/// ``` -/// -/// The documentation strings are optional. If present, they will be added= to the type's -/// definition, or the field getter and setter methods they are attached t= o. -/// -/// It is also possible to create a alias register by using the `=3D> ALIA= S` syntax. This is useful -/// for cases where a register's interpretation depends on the context: -/// -/// ```no_run -/// register!(SCRATCH @ 0x00000200, "Scratch register" { -/// 31:0 value as u32, "Raw value"; -/// }); -/// -/// register!(SCRATCH_BOOT_STATUS =3D> SCRATCH, "Boot status of the firmwa= re" { -/// 0:0 completed as bool, "Whether the firmware has completed boo= ting"; -/// }); -/// ``` -/// -/// In this example, `SCRATCH_0_BOOT_STATUS` uses the same I/O address as = `SCRATCH`, while also -/// providing its own `completed` field. -/// -/// ## Relative registers -/// -/// A register can be defined as being accessible from a fixed offset of a= provided base. For -/// instance, imagine the following I/O space: -/// -/// ```text -/// +-----------------------------+ -/// | ... | -/// | | -/// 0x100--->+------------CPU0-------------+ -/// | | -/// 0x110--->+-----------------------------+ -/// | CPU_CTL | -/// +-----------------------------+ -/// | ... | -/// | | -/// | | -/// 0x200--->+------------CPU1-------------+ -/// | | -/// 0x210--->+-----------------------------+ -/// | CPU_CTL | -/// +-----------------------------+ -/// | ... | -/// +-----------------------------+ -/// ``` -/// -/// `CPU0` and `CPU1` both have a `CPU_CTL` register that starts at offset= `0x10` of their I/O -/// space segment. Since both instances of `CPU_CTL` share the same layout= , we don't want to define -/// them twice and would prefer a way to select which one to use from a si= ngle definition -/// -/// This can be done using the `Base[Offset]` syntax when specifying the r= egister's address. -/// -/// `Base` is an arbitrary type (typically a ZST) to be used as a generic = parameter of the -/// [`RegisterBase`] trait to provide the base as a constant, i.e. each ty= pe providing a base for -/// this register needs to implement `RegisterBase`. Here is the abo= ve example translated -/// into code: -/// -/// ```no_run -/// // Type used to identify the base. -/// pub(crate) struct CpuCtlBase; -/// -/// // ZST describing `CPU0`. -/// struct Cpu0; -/// impl RegisterBase for Cpu0 { -/// const BASE: usize =3D 0x100; -/// } -/// // Singleton of `CPU0` used to identify it. -/// const CPU0: Cpu0 =3D Cpu0; -/// -/// // ZST describing `CPU1`. -/// struct Cpu1; -/// impl RegisterBase for Cpu1 { -/// const BASE: usize =3D 0x200; -/// } -/// // Singleton of `CPU1` used to identify it. -/// const CPU1: Cpu1 =3D Cpu1; -/// -/// // This makes `CPU_CTL` accessible from all implementors of `RegisterB= ase`. -/// register!(CPU_CTL @ CpuCtlBase[0x10], "CPU core control" { -/// 0:0 start as bool, "Start the CPU core"; -/// }); -/// -/// // The `read`, `write` and `update` methods of relative registers take= an extra `base` argument -/// // that is used to resolve its final address by adding its `BASE` to t= he offset of the -/// // register. -/// -/// // Start `CPU0`. -/// CPU_CTL::update(bar, &CPU0, |r| r.set_start(true)); -/// -/// // Start `CPU1`. -/// CPU_CTL::update(bar, &CPU1, |r| r.set_start(true)); -/// -/// // Aliases can also be defined for relative register. -/// register!(CPU_CTL_ALIAS =3D> CpuCtlBase[CPU_CTL], "Alias to CPU core c= ontrol" { -/// 1:1 alias_start as bool, "Start the aliased CPU core"; -/// }); -/// -/// // Start the aliased `CPU0`. -/// CPU_CTL_ALIAS::update(bar, &CPU0, |r| r.set_alias_start(true)); -/// ``` -/// -/// ## Arrays of registers -/// -/// Some I/O areas contain consecutive values that can be interpreted in t= he same way. These areas -/// can be defined as an array of identical registers, allowing them to be= accessed by index with -/// compile-time or runtime bound checking. Simply define their address as= `Address[Size]`, and add -/// an `idx` parameter to their `read`, `write` and `update` methods: -/// -/// ```no_run -/// # fn no_run() -> Result<(), Error> { -/// # fn get_scratch_idx() -> usize { -/// # 0x15 -/// # } -/// // Array of 64 consecutive registers with the same layout starting at = offset `0x80`. -/// register!(SCRATCH @ 0x00000080[64], "Scratch registers" { -/// 31:0 value as u32; -/// }); -/// -/// // Read scratch register 0, i.e. I/O address `0x80`. -/// let scratch_0 =3D SCRATCH::read(bar, 0).value(); -/// // Read scratch register 15, i.e. I/O address `0x80 + (15 * 4)`. -/// let scratch_15 =3D SCRATCH::read(bar, 15).value(); -/// -/// // This is out of bounds and won't build. -/// // let scratch_128 =3D SCRATCH::read(bar, 128).value(); -/// -/// // Runtime-obtained array index. -/// let scratch_idx =3D get_scratch_idx(); -/// // Access on a runtime index returns an error if it is out-of-bounds. -/// let some_scratch =3D SCRATCH::try_read(bar, scratch_idx)?.value(); -/// -/// // Alias to a particular register in an array. -/// // Here `SCRATCH[8]` is used to convey the firmware exit code. -/// register!(FIRMWARE_STATUS =3D> SCRATCH[8], "Firmware exit status code"= { -/// 7:0 status as u8; -/// }); -/// -/// let status =3D FIRMWARE_STATUS::read(bar).status(); -/// -/// // Non-contiguous register arrays can be defined by adding a stride pa= rameter. -/// // Here, each of the 16 registers of the array are separated by 8 byte= s, meaning that the -/// // registers of the two declarations below are interleaved. -/// register!(SCRATCH_INTERLEAVED_0 @ 0x000000c0[16 ; 8], "Scratch registe= rs bank 0" { -/// 31:0 value as u32; -/// }); -/// register!(SCRATCH_INTERLEAVED_1 @ 0x000000c4[16 ; 8], "Scratch registe= rs bank 1" { -/// 31:0 value as u32; -/// }); -/// # Ok(()) -/// # } -/// ``` -/// -/// ## Relative arrays of registers -/// -/// Combining the two features described in the sections above, arrays of = registers accessible from -/// a base can also be defined: -/// -/// ```no_run -/// # fn no_run() -> Result<(), Error> { -/// # fn get_scratch_idx() -> usize { -/// # 0x15 -/// # } -/// // Type used as parameter of `RegisterBase` to specify the base. -/// pub(crate) struct CpuCtlBase; -/// -/// // ZST describing `CPU0`. -/// struct Cpu0; -/// impl RegisterBase for Cpu0 { -/// const BASE: usize =3D 0x100; -/// } -/// // Singleton of `CPU0` used to identify it. -/// const CPU0: Cpu0 =3D Cpu0; -/// -/// // ZST describing `CPU1`. -/// struct Cpu1; -/// impl RegisterBase for Cpu1 { -/// const BASE: usize =3D 0x200; -/// } -/// // Singleton of `CPU1` used to identify it. -/// const CPU1: Cpu1 =3D Cpu1; -/// -/// // 64 per-cpu scratch registers, arranged as an contiguous array. -/// register!(CPU_SCRATCH @ CpuCtlBase[0x00000080[64]], "Per-CPU scratch r= egisters" { -/// 31:0 value as u32; -/// }); -/// -/// let cpu0_scratch_0 =3D CPU_SCRATCH::read(bar, &Cpu0, 0).value(); -/// let cpu1_scratch_15 =3D CPU_SCRATCH::read(bar, &Cpu1, 15).value(); -/// -/// // This won't build. -/// // let cpu0_scratch_128 =3D CPU_SCRATCH::read(bar, &Cpu0, 128).value(); -/// -/// // Runtime-obtained array index. -/// let scratch_idx =3D get_scratch_idx(); -/// // Access on a runtime value returns an error if it is out-of-bounds. -/// let cpu0_some_scratch =3D CPU_SCRATCH::try_read(bar, &Cpu0, scratch_id= x)?.value(); -/// -/// // `SCRATCH[8]` is used to convey the firmware exit code. -/// register!(CPU_FIRMWARE_STATUS =3D> CpuCtlBase[CPU_SCRATCH[8]], -/// "Per-CPU firmware exit status code" { -/// 7:0 status as u8; -/// }); -/// -/// let cpu0_status =3D CPU_FIRMWARE_STATUS::read(bar, &Cpu0).status(); -/// -/// // Non-contiguous register arrays can be defined by adding a stride pa= rameter. -/// // Here, each of the 16 registers of the array are separated by 8 byte= s, meaning that the -/// // registers of the two declarations below are interleaved. -/// register!(CPU_SCRATCH_INTERLEAVED_0 @ CpuCtlBase[0x00000d00[16 ; 8]], -/// "Scratch registers bank 0" { -/// 31:0 value as u32; -/// }); -/// register!(CPU_SCRATCH_INTERLEAVED_1 @ CpuCtlBase[0x00000d04[16 ; 8]], -/// "Scratch registers bank 1" { -/// 31:0 value as u32; -/// }); -/// # Ok(()) -/// # } -/// ``` -macro_rules! register { - // Creates a register at a fixed offset of the MMIO space. - ($name:ident @ $offset:literal $(, $comment:literal)? { $($fields:tt)*= } ) =3D> { - bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); - register!(@io_fixed $name @ $offset); - }; - - // Creates an alias register of fixed offset register `alias` with its= own fields. - ($name:ident =3D> $alias:ident $(, $comment:literal)? { $($fields:tt)*= } ) =3D> { - bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); - register!(@io_fixed $name @ $alias::OFFSET); - }; - - // Creates a register at a relative offset from a base address provide= r. - ($name:ident @ $base:ty [ $offset:literal ] $(, $comment:literal)? { $= ($fields:tt)* } ) =3D> { - bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); - register!(@io_relative $name @ $base [ $offset ]); - }; - - // Creates an alias register of relative offset register `alias` with = its own fields. - ($name:ident =3D> $base:ty [ $alias:ident ] $(, $comment:literal)? { $= ($fields:tt)* }) =3D> { - bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); - register!(@io_relative $name @ $base [ $alias::OFFSET ]); - }; - - // Creates an array of registers at a fixed offset of the MMIO space. - ( - $name:ident @ $offset:literal [ $size:expr ; $stride:expr ] $(, $c= omment:literal)? { - $($fields:tt)* - } - ) =3D> { - static_assert!(::core::mem::size_of::() <=3D $stride); - bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); - register!(@io_array $name @ $offset [ $size ; $stride ]); - }; - - // Shortcut for contiguous array of registers (stride =3D=3D size of e= lement). - ( - $name:ident @ $offset:literal [ $size:expr ] $(, $comment:literal)= ? { - $($fields:tt)* - } - ) =3D> { - register!($name @ $offset [ $size ; ::core::mem::size_of::() = ] $(, $comment)? { - $($fields)* - } ); - }; - - // Creates an array of registers at a relative offset from a base addr= ess provider. - ( - $name:ident @ $base:ty [ $offset:literal [ $size:expr ; $stride:ex= pr ] ] - $(, $comment:literal)? { $($fields:tt)* } - ) =3D> { - static_assert!(::core::mem::size_of::() <=3D $stride); - bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); - register!(@io_relative_array $name @ $base [ $offset [ $size ; $st= ride ] ]); - }; - - // Shortcut for contiguous array of relative registers (stride =3D=3D = size of element). - ( - $name:ident @ $base:ty [ $offset:literal [ $size:expr ] ] $(, $com= ment:literal)? { - $($fields:tt)* - } - ) =3D> { - register!($name @ $base [ $offset [ $size ; ::core::mem::size_of::= () ] ] - $(, $comment)? { $($fields)* } ); - }; - - // Creates an alias of register `idx` of relative array of registers `= alias` with its own - // fields. - ( - $name:ident =3D> $base:ty [ $alias:ident [ $idx:expr ] ] $(, $comm= ent:literal)? { - $($fields:tt)* - } - ) =3D> { - static_assert!($idx < $alias::SIZE); - bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); - register!(@io_relative $name @ $base [ $alias::OFFSET + $idx * $al= ias::STRIDE ] ); - }; - - // Creates an alias of register `idx` of array of registers `alias` wi= th its own fields. - // This rule belongs to the (non-relative) register arrays set, but ne= eds to be put last - // to avoid it being interpreted in place of the relative register arr= ay alias rule. - ($name:ident =3D> $alias:ident [ $idx:expr ] $(, $comment:literal)? { = $($fields:tt)* }) =3D> { - static_assert!($idx < $alias::SIZE); - bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); - register!(@io_fixed $name @ $alias::OFFSET + $idx * $alias::STRIDE= ); - }; - - // Generates the IO accessors for a fixed offset register. - (@io_fixed $name:ident @ $offset:expr) =3D> { - #[allow(dead_code)] - impl $name { - pub(crate) const OFFSET: usize =3D $offset; - - /// Read the register from its address in `io`. - #[inline(always)] - pub(crate) fn read(io: &T) -> Self where - T: ::core::ops::Deref, - I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable, - { - Self(io.read32($offset)) - } - - /// Write the value contained in `self` to the register addres= s in `io`. - #[inline(always)] - pub(crate) fn write(self, io: &T) where - T: ::core::ops::Deref, - I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable, - { - io.write32(self.0, $offset) - } - - /// Read the register from its address in `io` and run `f` on = its value to obtain a new - /// value to write back. - #[inline(always)] - pub(crate) fn update( - io: &T, - f: F, - ) where - T: ::core::ops::Deref, - I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable, - F: ::core::ops::FnOnce(Self) -> Self, - { - let reg =3D f(Self::read(io)); - reg.write(io); - } - } - }; - - // Generates the IO accessors for a relative offset register. - (@io_relative $name:ident @ $base:ty [ $offset:expr ]) =3D> { - #[allow(dead_code)] - impl $name { - pub(crate) const OFFSET: usize =3D $offset; - - /// Read the register from `io`, using the base address provid= ed by `base` and adding - /// the register's offset to it. - #[inline(always)] - pub(crate) fn read( - io: &T, - #[allow(unused_variables)] - base: &B, - ) -> Self where - T: ::core::ops::Deref, - I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable, - B: crate::regs::macros::RegisterBase<$base>, - { - const OFFSET: usize =3D $name::OFFSET; - - let value =3D io.read32( - >::BASE = + OFFSET - ); - - Self(value) - } - - /// Write the value contained in `self` to `io`, using the bas= e address provided by - /// `base` and adding the register's offset to it. - #[inline(always)] - pub(crate) fn write( - self, - io: &T, - #[allow(unused_variables)] - base: &B, - ) where - T: ::core::ops::Deref, - I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable, - B: crate::regs::macros::RegisterBase<$base>, - { - const OFFSET: usize =3D $name::OFFSET; - - io.write32( - self.0, - >::BASE = + OFFSET - ); - } - - /// Read the register from `io`, using the base address provid= ed by `base` and adding - /// the register's offset to it, then run `f` on its value to = obtain a new value to - /// write back. - #[inline(always)] - pub(crate) fn update( - io: &T, - base: &B, - f: F, - ) where - T: ::core::ops::Deref, - I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable, - B: crate::regs::macros::RegisterBase<$base>, - F: ::core::ops::FnOnce(Self) -> Self, - { - let reg =3D f(Self::read(io, base)); - reg.write(io, base); - } - } - }; - - // Generates the IO accessors for an array of registers. - (@io_array $name:ident @ $offset:literal [ $size:expr ; $stride:expr ]= ) =3D> { - #[allow(dead_code)] - impl $name { - pub(crate) const OFFSET: usize =3D $offset; - pub(crate) const SIZE: usize =3D $size; - pub(crate) const STRIDE: usize =3D $stride; - - /// Read the array register at index `idx` from its address in= `io`. - #[inline(always)] - pub(crate) fn read( - io: &T, - idx: usize, - ) -> Self where - T: ::core::ops::Deref, - I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable, - { - build_assert!(idx < Self::SIZE); - - let offset =3D Self::OFFSET + (idx * Self::STRIDE); - let value =3D io.read32(offset); - - Self(value) - } - - /// Write the value contained in `self` to the array register = with index `idx` in `io`. - #[inline(always)] - pub(crate) fn write( - self, - io: &T, - idx: usize - ) where - T: ::core::ops::Deref, - I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable, - { - build_assert!(idx < Self::SIZE); - - let offset =3D Self::OFFSET + (idx * Self::STRIDE); - - io.write32(self.0, offset); - } - - /// Read the array register at index `idx` in `io` and run `f`= on its value to obtain a - /// new value to write back. - #[inline(always)] - pub(crate) fn update( - io: &T, - idx: usize, - f: F, - ) where - T: ::core::ops::Deref, - I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable, - F: ::core::ops::FnOnce(Self) -> Self, - { - let reg =3D f(Self::read(io, idx)); - reg.write(io, idx); - } - - /// Read the array register at index `idx` from its address in= `io`. - /// - /// The validity of `idx` is checked at run-time, and `EINVAL`= is returned is the - /// access was out-of-bounds. - #[inline(always)] - pub(crate) fn try_read( - io: &T, - idx: usize, - ) -> ::kernel::error::Result where - T: ::core::ops::Deref, - I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable, - { - if idx < Self::SIZE { - Ok(Self::read(io, idx)) - } else { - Err(EINVAL) - } - } - - /// Write the value contained in `self` to the array register = with index `idx` in `io`. - /// - /// The validity of `idx` is checked at run-time, and `EINVAL`= is returned is the - /// access was out-of-bounds. - #[inline(always)] - pub(crate) fn try_write( - self, - io: &T, - idx: usize, - ) -> ::kernel::error::Result where - T: ::core::ops::Deref, - I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable, - { - if idx < Self::SIZE { - Ok(self.write(io, idx)) - } else { - Err(EINVAL) - } - } - - /// Read the array register at index `idx` in `io` and run `f`= on its value to obtain a - /// new value to write back. - /// - /// The validity of `idx` is checked at run-time, and `EINVAL`= is returned is the - /// access was out-of-bounds. - #[inline(always)] - pub(crate) fn try_update( - io: &T, - idx: usize, - f: F, - ) -> ::kernel::error::Result where - T: ::core::ops::Deref, - I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable, - F: ::core::ops::FnOnce(Self) -> Self, - { - if idx < Self::SIZE { - Ok(Self::update(io, idx, f)) - } else { - Err(EINVAL) - } - } - } - }; - - // Generates the IO accessors for an array of relative registers. - ( - @io_relative_array $name:ident @ $base:ty - [ $offset:literal [ $size:expr ; $stride:expr ] ] - ) =3D> { - #[allow(dead_code)] - impl $name { - pub(crate) const OFFSET: usize =3D $offset; - pub(crate) const SIZE: usize =3D $size; - pub(crate) const STRIDE: usize =3D $stride; - - /// Read the array register at index `idx` from `io`, using th= e base address provided - /// by `base` and adding the register's offset to it. - #[inline(always)] - pub(crate) fn read( - io: &T, - #[allow(unused_variables)] - base: &B, - idx: usize, - ) -> Self where - T: ::core::ops::Deref, - I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable, - B: crate::regs::macros::RegisterBase<$base>, - { - build_assert!(idx < Self::SIZE); - - let offset =3D >::BASE + - Self::OFFSET + (idx * Self::STRIDE); - let value =3D io.read32(offset); - - Self(value) - } - - /// Write the value contained in `self` to `io`, using the bas= e address provided by - /// `base` and adding the offset of array register `idx` to it. - #[inline(always)] - pub(crate) fn write( - self, - io: &T, - #[allow(unused_variables)] - base: &B, - idx: usize - ) where - T: ::core::ops::Deref, - I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable, - B: crate::regs::macros::RegisterBase<$base>, - { - build_assert!(idx < Self::SIZE); - - let offset =3D >::BASE + - Self::OFFSET + (idx * Self::STRIDE); - - io.write32(self.0, offset); - } - - /// Read the array register at index `idx` from `io`, using th= e base address provided - /// by `base` and adding the register's offset to it, then run= `f` on its value to - /// obtain a new value to write back. - #[inline(always)] - pub(crate) fn update( - io: &T, - base: &B, - idx: usize, - f: F, - ) where - T: ::core::ops::Deref, - I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable, - B: crate::regs::macros::RegisterBase<$base>, - F: ::core::ops::FnOnce(Self) -> Self, - { - let reg =3D f(Self::read(io, base, idx)); - reg.write(io, base, idx); - } - - /// Read the array register at index `idx` from `io`, using th= e base address provided - /// by `base` and adding the register's offset to it. - /// - /// The validity of `idx` is checked at run-time, and `EINVAL`= is returned is the - /// access was out-of-bounds. - #[inline(always)] - pub(crate) fn try_read( - io: &T, - base: &B, - idx: usize, - ) -> ::kernel::error::Result where - T: ::core::ops::Deref, - I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable, - B: crate::regs::macros::RegisterBase<$base>, - { - if idx < Self::SIZE { - Ok(Self::read(io, base, idx)) - } else { - Err(EINVAL) - } - } - - /// Write the value contained in `self` to `io`, using the bas= e address provided by - /// `base` and adding the offset of array register `idx` to it. - /// - /// The validity of `idx` is checked at run-time, and `EINVAL`= is returned is the - /// access was out-of-bounds. - #[inline(always)] - pub(crate) fn try_write( - self, - io: &T, - base: &B, - idx: usize, - ) -> ::kernel::error::Result where - T: ::core::ops::Deref, - I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable, - B: crate::regs::macros::RegisterBase<$base>, - { - if idx < Self::SIZE { - Ok(self.write(io, base, idx)) - } else { - Err(EINVAL) - } - } - - /// Read the array register at index `idx` from `io`, using th= e base address provided - /// by `base` and adding the register's offset to it, then run= `f` on its value to - /// obtain a new value to write back. - /// - /// The validity of `idx` is checked at run-time, and `EINVAL`= is returned is the - /// access was out-of-bounds. - #[inline(always)] - pub(crate) fn try_update( - io: &T, - base: &B, - idx: usize, - f: F, - ) -> ::kernel::error::Result where - T: ::core::ops::Deref, - I: ::kernel::io::IoKnownSize + ::kernel::io::IoCapable, - B: crate::regs::macros::RegisterBase<$base>, - F: ::core::ops::FnOnce(Self) -> Self, - { - if idx < Self::SIZE { - Ok(Self::update(io, base, idx, f)) - } else { - Err(EINVAL) - } - } - } - }; -} --=20 2.53.0