From nobody Wed Jun 17 01:38:28 2026 Received: from LO0P265CU003.outbound.protection.outlook.com (mail-uksouthazon11022092.outbound.protection.outlook.com [52.101.96.92]) (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 1830B429811; Thu, 11 Jun 2026 16:28:33 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.96.92 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195316; cv=fail; b=BPwlDW7m7Dym5DQ0u9wNXQ0jR5+xC0IJFbNadmfL23XtnD76gEp/enpMTQ81466ToVkZPlJPTQ0sTQydrGIynqDZxbtwICwdRat1Yr8LBk+yOasUwvxHhUnBrvVxDjYsXTLQVXXcfDyZDgOE13aU62u4diZMRQA2R7pK01PwFCs= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195316; c=relaxed/simple; bh=SrFfOHPnj3XpIXHr75f9FycoGL9SYFYygZ9kS+LCZg0=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=HIA9n7aK9Uem92OSUMGHTgQuhJfIi/BGEe+mt+TeZXRPd8W8ceC+jH4jZddVsxMnSymAoWxJUZYqUUe+6dJ/eB5qHnB/lG7Ukvjy8CLXetkzH9y1hRr9n6/BsSqitkUzwhodOusXPajCaLOHAMT2bULJFmnUewLroxTFtA2sjfE= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=I9rlsiI7; arc=fail smtp.client-ip=52.101.96.92 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="I9rlsiI7" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=SZhisqnEChievMbXMKZB14JjCS5o9IyZUO+SISBQKT8PKbC7d1eJfcRJCXn7PYizhyfSczrDWmbnYv1IKzGXjeqzTc/JHMLRMluLP2GWmZmbUrphUhyt+CpkWvcJCtAWI3ZbTlOhe0SmFBAXPtFxKESZTjzZFyzx6HlqkbAhXFHePaRcaidJQXQSRrhfhzGBNXdVuDroxDXYeYrF3fu3N8xZbN1V1EvF1bNdV+g9FsOOuDJdAXJtK01wVg7kUMZjHVf/36x6dPxoz8lyy2Kw3wMPe3i2mBpUf6KhXNsWuc0kTe7vC2W29Ym29keUyzwt9Tjve7q9Ka9S0Nj6EONHBw== 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=9lH390IS2xn+Ehy2wop3ztGAqHMj2r1XssAT/o5Yxo8=; b=ppvnYbafJLfM7fBcURtKgGFe3vh/nX7mTIrELH+Karv+vY/QzPTZPjPfrMoySYS9cA1vkZ/0pRE6cRe0eswf9SBfwVSMOSj6TSd941xzzrJ2k5aMLjJ8fAl4IY6vrdi95j1KJWpf8/NloF/pQow2ScXB1VpXvZT1xBBkt90SIc1LC5olA8Fs94U5NbFi745RZUd/zwrDeOVIcoXsq6xtL72LcoWnBxEar+iFM1tq+hDj+V3O00tXgMeF4cSl9tCHJtYHauhyC16NFF2vbb2Pq7GPcuzVhbOsJQW3f9Cm+C9CLgzpAaCaTRB4lAwNiD5VbUm8RUXMOoGDb3t22UteFA== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=9lH390IS2xn+Ehy2wop3ztGAqHMj2r1XssAT/o5Yxo8=; b=I9rlsiI7kuYjZUFPf2xaqSX2Qk1fNyVlel0L2sbmw1R5ia2Lwu0pzxAg/Ulo9X1nK2l4zx8DivMSyf7KfXXDKfG0of82LoJTRRBya5MY+0z0c9KOsODM85nnZngi830hqjULywCljBGMXSv/69GHJxSFohxsvvhnEmNQfNAjoGI= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO2P265MB3263.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:156::7) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.13; Thu, 11 Jun 2026 16:28:23 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:23 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:03 +0100 Subject: [PATCH v4 01/20] rust: io: add dynamically-sized `Region` type Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-1-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195301; l=17117; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=SrFfOHPnj3XpIXHr75f9FycoGL9SYFYygZ9kS+LCZg0=; b=NzECPXyh8VRDQLPuHusW0leQ6OYgcE9njCfUsgOPqtFHbLE5o9/WE2eVp9z4crrFCVE8HsADE 3TcQk0j0GvbBo0gV8+DjyVt2lY7V3Y4w0/ZjrcDPcakDc/GsmVF3S0G X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO2P265MB3263:EE_ X-MS-Office365-Filtering-Correlation-Id: 4ca0c1bb-d414-4695-eb02-08dec7d674e2 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|10070799003|1800799024|7416014|376014|366016|23010399003|18002099003|22082099003|921020|5023799004|6133799003|56012099006; X-Microsoft-Antispam-Message-Info: 1u1u/PKb7xw55r3BA2Q9cSYvWlKg5w5WqPMIgjbjx2QA0WuloEwUxUtLMp93Exe2UrD2pOFoYb8neHyDurNUhhZ3RCWbX365T8HYWTegFyH9j0ubfst+d1xWOWbl88CecOCaewJCF23anC518z5GZjM+8c3K7uu9KewgUPsl57Zn0RJ1t2fh2iMqYN2HWjMTr9k+naNDAqlWmtooSgzOAExCDL64XAm4tP6br/15tHjVifoKyaamN8m5AacshEbf4Y60fQH08dTkaX437LZHbTD7/N+PezMFsepozjTzfJhty5ZF+dzKSBupGWYQnBdiraFvObXCeb9zKyzvYLa2KiYxopj2Syrx+7e+NkZJ1EZwvGyRjto4dTMay7jtaClU3mpN+gvHgj5tQhaUFSGLt6TagKjBQlFGTZaywvHPQeJr0m/cyHkdtQ0ttdWE490CzYS5q00E4W9ne2R34kTSZO5/1lfNrYMfXq03ZE+FkGJ7cIJq+mmtubEm++A/AxOG+EuFMyTpcLS9vlIOqC1v4Vel9csa2N1eXS5+zUMG07rHY+pDyJ6G6xtYeO/fs+FLxgs2Ugps3TmViDEXynttDiZ/od+h9T3N0sYYrvKA3L1U1ehoqmL/xelcB/OyiXQ9yjPyqvAbzyBQWyxWrdblCnKhlCkp2pMZxBQzPzM6SxUop5Hvhh7zV1Qw4nKvBki+WcIDkx0OqmBW3xbrRp+ya3ptRO5dTiMM7uXy3bzx+tTO3wFC0QyjyDsbPx7PZaRk X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(10070799003)(1800799024)(7416014)(376014)(366016)(23010399003)(18002099003)(22082099003)(921020)(5023799004)(6133799003)(56012099006);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?dk5mN2gzMWNmbC9sSzdTZGt1R3loUmJGT3M1WkkvZTFkZXVYRDg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TjhQdVQ3eUJYbFBNS0l5SFJVWUl4M0FwMWRieVArSUR0MUpsS1pPK3I1?= =?utf-8?B?S2I3VWppUHVtcSs3ZndoRVZsR25adXFpRXJVSEE3OFg1QXBQVDJOaWhFWGgr?= =?utf-8?B?U3k5UmtCTnBzRCt6SWlHNHdJakV6cVF6KzczaThKUWRRSnVuNmlaQ0wxL0FW?= =?utf-8?B?YUNmYkxFZU9nN2F6SGp5YklnM3dnbW11dEo4WkpLSWxaZkcxY1hvOVdsbzVW?= =?utf-8?B?WVoyNnNCQytHcHJEZUpUOGJDS1FlT1RweEtSdjlPQmtuMVVZRE1OYnJpMnhC?= =?utf-8?B?dkFaZU52RkRzTEtsb3Vad3lCR2xjSWRydEQvZXlNTFNQK05yaUMreVljeTh0?= =?utf-8?B?ZWM5K1lRcjlBRmNSMWZtdnhzSVhoRnFkLzNhekJFNkFoYlR5OVdHN2d6SHQ0?= =?utf-8?B?Wkx3bTZOcEJFYjhXTEdhTjIzVWVjeXdrazV1MWw1T3EzOGlLTmRMcnZVVDM1?= =?utf-8?B?Mmo3WVFqMGZIUjRLR3lXKzFsZWxqWmViNmFLdk1zR0RET292UGZuUT09?= X-OriginatorOrg: garyguo.net X-MS-Exchange-CrossTenant-Network-Message-Id: 4ca0c1bb-d414-4695-eb02-08dec7d674e2 X-MS-Exchange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:23.2124 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: zaZaGC+bNo6NpB5x9cYCav8HZmgMGpqahnsPRkaUDauu2QcGXTLrdg7SZV7PBePv2Wlbz2GyQYrg5FluzvR8bA== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO2P265MB3263 Currently many I/O related structs carry a `SIZE` parameter to denote the minimum size of the I/O region, while they also carry a field indicating the actual size. Proliferation of the pattern creates a lot of duplicated code, and makes it hard to create typed views of I/O. Introduce a `Region` type that carries the `SIZE` parameter. It is a wrapper of `[u8]`, which makes it dynamically sized with a metadata of `usize`. This way, pointers to `Region` naturally carry size information. This type is required to be 4-byte aligned. Expose the minimum size information via `MIN_SIZE` constant of the `KnownSize` trait. Similarly, expose the minimum alignment information via `KnownSize::MIN_ALIGN`. With these changes, it is possible to add an associated type to `Io` trait to represent the type of I/O region. For untyped regions, this is the newly added `Region` type. Remove `IoKnownSize` as it is no longer necessary. Use the same mechanism to indicate minimum size of PCI config spaces. Signed-off-by: Gary Guo Acked-by: Miguel Ojeda Suggested-by: Danilo Krummrich --- rust/kernel/devres.rs | 6 +-- rust/kernel/io.rs | 130 +++++++++++++++++++++++++++++++++-------------= ---- rust/kernel/lib.rs | 3 ++ rust/kernel/pci.rs | 1 - rust/kernel/pci/io.rs | 40 +++++++--------- rust/kernel/ptr.rs | 12 +++++ 6 files changed, 118 insertions(+), 74 deletions(-) diff --git a/rust/kernel/devres.rs b/rust/kernel/devres.rs index 11ce500e9b76..ed30ccc6e68e 100644 --- a/rust/kernel/devres.rs +++ b/rust/kernel/devres.rs @@ -68,7 +68,6 @@ struct Inner { /// devres::Devres, /// io::{ /// Io, -/// IoKnownSize, /// Mmio, /// MmioRaw, /// PhysAddr, // @@ -297,10 +296,7 @@ pub fn device(&self) -> &Device { /// use kernel::{ /// device::Core, /// devres::Devres, - /// io::{ - /// Io, - /// IoKnownSize, // - /// }, + /// io::Io, /// pci, // /// }; /// diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index fcc7678fd9e3..bef571dad6eb 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -6,7 +6,11 @@ =20 use crate::{ bindings, - prelude::*, // + prelude::*, + ptr::{ + Alignment, + KnownSize, // + }, // }; =20 pub mod mem; @@ -31,6 +35,58 @@ /// `CONFIG_PHYS_ADDR_T_64BIT`, and it can be a u64 even on 32-bit archite= ctures. pub type ResourceSize =3D bindings::resource_size_t; =20 +/// Untyped I/O region. +/// +/// This type can be used when an I/O region without known type informatio= n has a compile-time known +/// minimum size (and a runtime known actual size). +/// +/// This must be 4-byte aligned. +/// +/// # Invariants +/// +/// Size of the region is at least as large as the `SIZE` generic paramete= r. +#[repr(C, align(4))] +pub struct Region { + inner: [u8], +} + +impl Region { + /// Create a raw mutable pointer from given base address and size. + /// + /// `size` should be at least as large as the minimum size `SIZE`, and= `base` and `size` should + /// be 4-byte aligned to uphold the type invariant. + /// + /// Just like other methods on raw pointers, it is not unsafe to creat= e a raw pointer + /// that does not uphold the type invariants. However such pointers ar= e not valid. + #[inline] + pub fn ptr_from_raw_parts_mut(base: *mut u8, size: usize) -> *mut Self= { + core::ptr::slice_from_raw_parts_mut(base, size) as *mut Region + } + + /// Create a raw mutable pointer from given base address and size. + /// + /// The alignment of `base` is checked, and `size` is checked against = the minimum size specified + /// via const generics. + #[inline] + pub fn ptr_try_from_raw_parts_mut(base: *mut u8, size: usize) -> Resul= t<*mut Self> { + if size < SIZE || base.align_offset(4) !=3D 0 || !size.is_multiple= _of(4) { + return Err(EINVAL); + } + + Ok(Self::ptr_from_raw_parts_mut(base, size)) + } +} + +impl KnownSize for Region { + const MIN_SIZE: usize =3D SIZE; + const MIN_ALIGN: Alignment =3D Alignment::new::<4>(); + + #[inline(always)] + fn size(p: *const Self) -> usize { + (p as *const [u8]).len() + } +} + /// Raw representation of an MMIO region. /// /// By itself, the existence of an instance of this structure does not pro= vide any guarantees that @@ -85,7 +141,6 @@ pub fn maxsize(&self) -> usize { /// ffi::c_void, /// io::{ /// Io, -/// IoKnownSize, /// Mmio, /// MmioRaw, /// PhysAddr, @@ -241,12 +296,25 @@ fn offset(self) -> usize { /// For MMIO regions, all widths (u8, u16, u32, and u64 on 64-bit systems)= are typically /// supported. For PCI configuration space, u8, u16, and u32 are supported= but u64 is not. pub trait Io { + /// Type of this I/O region. For untyped regions, [`Region`] can be us= ed. + type Target: ?Sized + KnownSize; + /// Returns the base address of this mapping. fn addr(&self) -> usize; =20 /// Returns the maximum size of this mapping. fn maxsize(&self) -> usize; =20 + /// Returns the absolute I/O address for a given `offset`, + /// performing compile-time bound checks. + // Always inline to optimize out error path of `build_assert`. + #[inline(always)] + fn io_addr_assert(&self, offset: usize) -> usize { + build_assert!(offset_valid::(offset, Self::Target::MIN_SIZE)); + + self.addr() + offset + } + /// Returns the absolute I/O address for a given `offset`, /// performing runtime bound checks. #[inline] @@ -336,7 +404,7 @@ fn try_write64(&self, value: u64, offset: usize) -> Res= ult #[inline(always)] fn read8(&self, offset: usize) -> u8 where - Self: IoKnownSize + IoCapable, + Self: IoCapable, { self.read(offset) } @@ -345,7 +413,7 @@ fn read8(&self, offset: usize) -> u8 #[inline(always)] fn read16(&self, offset: usize) -> u16 where - Self: IoKnownSize + IoCapable, + Self: IoCapable, { self.read(offset) } @@ -354,7 +422,7 @@ fn read16(&self, offset: usize) -> u16 #[inline(always)] fn read32(&self, offset: usize) -> u32 where - Self: IoKnownSize + IoCapable, + Self: IoCapable, { self.read(offset) } @@ -363,7 +431,7 @@ fn read32(&self, offset: usize) -> u32 #[inline(always)] fn read64(&self, offset: usize) -> u64 where - Self: IoKnownSize + IoCapable, + Self: IoCapable, { self.read(offset) } @@ -372,7 +440,7 @@ fn read64(&self, offset: usize) -> u64 #[inline(always)] fn write8(&self, value: u8, offset: usize) where - Self: IoKnownSize + IoCapable, + Self: IoCapable, { self.write(offset, value) } @@ -381,7 +449,7 @@ fn write8(&self, value: u8, offset: usize) #[inline(always)] fn write16(&self, value: u16, offset: usize) where - Self: IoKnownSize + IoCapable, + Self: IoCapable, { self.write(offset, value) } @@ -390,7 +458,7 @@ fn write16(&self, value: u16, offset: usize) #[inline(always)] fn write32(&self, value: u32, offset: usize) where - Self: IoKnownSize + IoCapable, + Self: IoCapable, { self.write(offset, value) } @@ -399,7 +467,7 @@ fn write32(&self, value: u32, offset: usize) #[inline(always)] fn write64(&self, value: u64, offset: usize) where - Self: IoKnownSize + IoCapable, + Self: IoCapable, { self.write(offset, value) } @@ -582,7 +650,7 @@ fn try_update(&self, location: L, f: F) -> Res= ult fn read(&self, location: L) -> T where L: IoLoc, - Self: IoKnownSize + IoCapable, + Self: IoCapable, { let address =3D self.io_addr_assert::(location.offset()= ); =20 @@ -614,7 +682,7 @@ fn read(&self, location: L) -> T fn write(&self, location: L, value: T) where L: IoLoc, - Self: IoKnownSize + IoCapable, + Self: IoCapable, { let address =3D self.io_addr_assert::(location.offset()= ); let io_value =3D value.into(); @@ -658,7 +726,7 @@ fn write_reg(&self, value: V) where L: IoLoc, V: LocatedRegister, - Self: IoKnownSize + IoCapable, + Self: IoCapable, { let (location, value) =3D value.into_io_op(); =20 @@ -690,7 +758,7 @@ fn write_reg(&self, value: V) fn update(&self, location: L, f: F) where L: IoLoc, - Self: IoKnownSize + IoCapable + Sized, + Self: IoCapable + Sized, F: FnOnce(T) -> T, { let address =3D self.io_addr_assert::(location.offset()= ); @@ -704,28 +772,6 @@ fn update(&self, location: L, f: F) } } =20 -/// Trait for types with a known size at compile time. -/// -/// This trait is implemented by I/O backends that have a compile-time kno= wn size, -/// enabling the use of infallible I/O accessors with compile-time bounds = checking. -/// -/// Types implementing this trait can use the infallible methods in [`Io`]= trait -/// (e.g., `read8`, `write32`), which require `Self: IoKnownSize` bound. -pub trait IoKnownSize: Io { - /// Minimum usable size of this region. - const MIN_SIZE: usize; - - /// Returns the absolute I/O address for a given `offset`, - /// performing compile-time bound checks. - // Always inline to optimize out error path of `build_assert`. - #[inline(always)] - fn io_addr_assert(&self, offset: usize) -> usize { - build_assert!(offset_valid::(offset, Self::MIN_SIZE)); - - self.addr() + offset - } -} - /// Implements [`IoCapable`] on `$mmio` for `$ty` using `$read_fn` and `$w= rite_fn`. macro_rules! impl_mmio_io_capable { ($mmio:ident, $(#[$attr:meta])* $ty:ty, $read_fn:ident, $write_fn:iden= t) =3D> { @@ -758,6 +804,8 @@ unsafe fn io_write(&self, value: $ty, address: usize) { ); =20 impl Io for Mmio { + type Target =3D Region; + /// Returns the base address of this mapping. #[inline] fn addr(&self) -> usize { @@ -771,10 +819,6 @@ fn maxsize(&self) -> usize { } } =20 -impl IoKnownSize for Mmio { - const MIN_SIZE: usize =3D SIZE; -} - impl Mmio { /// Converts an `MmioRaw` into an `Mmio` instance, providing the acces= sors to the MMIO mapping. /// @@ -798,6 +842,8 @@ pub unsafe fn from_raw(raw: &MmioRaw) -> &Self { pub struct RelaxedMmio(Mmio); =20 impl Io for RelaxedMmio { + type Target =3D Region; + #[inline] fn addr(&self) -> usize { self.0.addr() @@ -809,10 +855,6 @@ fn maxsize(&self) -> usize { } } =20 -impl IoKnownSize for RelaxedMmio { - const MIN_SIZE: usize =3D SIZE; -} - impl Mmio { /// Returns a [`RelaxedMmio`] reference that performs relaxed I/O oper= ations. /// diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 9512af7156df..68f4d9a3425d 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -16,6 +16,9 @@ // Please see https://github.com/Rust-for-Linux/linux/issues/2 for details= on // the unstable features in use. // +// Stable since Rust 1.87.0. +#![feature(unsigned_is_multiple_of)] +// // Stable since Rust 1.89.0. #![feature(generic_arg_infer)] // diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs index 5071cae6543f..c6d6bd8f251d 100644 --- a/rust/kernel/pci.rs +++ b/rust/kernel/pci.rs @@ -43,7 +43,6 @@ pub use self::io::{ Bar, ConfigSpace, - ConfigSpaceKind, ConfigSpaceSize, Extended, Normal, // diff --git a/rust/kernel/pci/io.rs b/rust/kernel/pci/io.rs index 0461e01aaa20..b4996aa059d8 100644 --- a/rust/kernel/pci/io.rs +++ b/rust/kernel/pci/io.rs @@ -10,11 +10,12 @@ io::{ Io, IoCapable, - IoKnownSize, Mmio, - MmioRaw, // + MmioRaw, + Region, // }, - prelude::*, // + prelude::*, + ptr::KnownSize, // }; use core::{ marker::PhantomData, @@ -46,28 +47,21 @@ pub const fn into_raw(self) -> usize { } } =20 -/// Marker type for normal (256-byte) PCI configuration space. -pub struct Normal; +/// Alias for normal (256-byte) PCI configuration space. +pub type Normal =3D Region<256>; =20 -/// Marker type for extended (4096-byte) PCIe configuration space. -pub struct Extended; +/// Alias for extended (4096-byte) PCIe configuration space. +pub type Extended =3D Region<4096>; =20 /// Trait for PCI configuration space size markers. /// /// This trait is implemented by [`Normal`] and [`Extended`] to provide /// compile-time knowledge of the configuration space size. -pub trait ConfigSpaceKind { - /// The size of this configuration space in bytes. - const SIZE: usize; -} +pub trait ConfigSpaceKind: KnownSize {} =20 -impl ConfigSpaceKind for Normal { - const SIZE: usize =3D 256; -} +impl ConfigSpaceKind for Normal {} =20 -impl ConfigSpaceKind for Extended { - const SIZE: usize =3D 4096; -} +impl ConfigSpaceKind for Extended {} =20 /// The PCI configuration space of a device. /// @@ -77,7 +71,7 @@ impl ConfigSpaceKind for Extended { /// The generic parameter `S` indicates the maximum size of the configurat= ion space. /// Use [`Normal`] for 256-byte legacy configuration space or [`Extended`]= for /// 4096-byte PCIe extended configuration space (default). -pub struct ConfigSpace<'a, S: ConfigSpaceKind =3D Extended> { +pub struct ConfigSpace<'a, S: ?Sized + ConfigSpaceKind =3D Extended> { pub(crate) pdev: &'a Device, _marker: PhantomData, } @@ -85,7 +79,7 @@ pub struct ConfigSpace<'a, S: ConfigSpaceKind =3D Extende= d> { /// Implements [`IoCapable`] on [`ConfigSpace`] for `$ty` using `$read_fn`= and `$write_fn`. macro_rules! impl_config_space_io_capable { ($ty:ty, $read_fn:ident, $write_fn:ident) =3D> { - impl<'a, S: ConfigSpaceKind> IoCapable<$ty> for ConfigSpace<'a, S>= { + impl<'a, S: ?Sized + ConfigSpaceKind> IoCapable<$ty> for ConfigSpa= ce<'a, S> { unsafe fn io_read(&self, address: usize) -> $ty { let mut val: $ty =3D 0; =20 @@ -118,7 +112,9 @@ unsafe fn io_write(&self, value: $ty, address: usize) { impl_config_space_io_capable!(u16, pci_read_config_word, pci_write_config_= word); impl_config_space_io_capable!(u32, pci_read_config_dword, pci_write_config= _dword); =20 -impl<'a, S: ConfigSpaceKind> Io for ConfigSpace<'a, S> { +impl<'a, S: ?Sized + ConfigSpaceKind> Io for ConfigSpace<'a, S> { + type Target =3D S; + /// Returns the base address of the I/O region. It is always 0 for con= figuration space. #[inline] fn addr(&self) -> usize { @@ -132,10 +128,6 @@ fn maxsize(&self) -> usize { } } =20 -impl<'a, S: ConfigSpaceKind> IoKnownSize for ConfigSpace<'a, S> { - const MIN_SIZE: usize =3D S::SIZE; -} - /// A PCI BAR to perform I/O-Operations on. /// /// I/O backend assumes that the device is little-endian and will automati= cally diff --git a/rust/kernel/ptr.rs b/rust/kernel/ptr.rs index 3f3e529e9f58..82acb531b17b 100644 --- a/rust/kernel/ptr.rs +++ b/rust/kernel/ptr.rs @@ -235,11 +235,20 @@ fn align_up(self, alignment: Alignment) -> Option { /// /// This is a generalization of [`size_of`] that works for dynamically siz= ed types. pub trait KnownSize { + /// Minimum size of this type known at compile-time. + const MIN_SIZE: usize; + + /// Minimum alignment of this type known at compile-time. + const MIN_ALIGN: Alignment; + /// Get the size of an object of this type in bytes, with the metadata= of the given pointer. fn size(p: *const Self) -> usize; } =20 impl KnownSize for T { + const MIN_SIZE: usize =3D size_of::(); + const MIN_ALIGN: Alignment =3D Alignment::of::(); + #[inline(always)] fn size(_: *const Self) -> usize { size_of::() @@ -247,6 +256,9 @@ fn size(_: *const Self) -> usize { } =20 impl KnownSize for [T] { + const MIN_SIZE: usize =3D 0; + const MIN_ALIGN: Alignment =3D Alignment::of::(); + #[inline(always)] fn size(p: *const Self) -> usize { p.len() * size_of::() --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from LO0P265CU003.outbound.protection.outlook.com (mail-uksouthazon11022092.outbound.protection.outlook.com [52.101.96.92]) (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 C6D9130674E; Thu, 11 Jun 2026 16:28:29 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.96.92 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195312; cv=fail; b=JAGnobbFchSrkBRaWHIpzy1E1YfNL8Mtj2WJ8lZzrifC0S4WUaWqKIfu3P6nAx4fH9wProhxXYKnSZWhWp/2/yqWmZ/8gsyt9GH8razSqpx6UTmR4RY6AqOMtMnkqjek1d7Tu2tpTCbZgW5AUxIM8nKEgORdqDkZ9qbx6STTqXU= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195312; c=relaxed/simple; bh=3aH7apFce79+fBGN0fdMkFZxI0uuMM4f7+WP97okgN0=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=pJdSMR2T3vy2Yup5BeZHb2puTzeJoWS/k8hlAwkzemBNi7SB4+NjQLU5nnzZKp6ZNdU4QZ7JGUDYNZ64dIyYMeUVkOeTQlMTA3HT6QlBDZQZk4Rm17umgkNlJPdr7r525mwTha1lpqnrXtGPjs0sd6ME8WRNvimqkBMsrnIAhdA= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=c/sEZR31; arc=fail smtp.client-ip=52.101.96.92 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="c/sEZR31" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=KZyMx+pitQt31vYp6Nyx4QsUenf2knBM+nKYSf0TQGMaMyUtA2b24X5JV9DEbSNEQjrkHqJaCe5G8Ar4ht5SsRrN+VeKkk5RryZw80NjBdzQXTxarze8uzI6ZBMu06ePteZKzNu1NvPuJ7+MaGc5STCoXhA04aqv6waM7KzWkcGG9nilj2Td3lP79zGhuBG9yWDvDRZEVxnUCr70Ax5v4nRc+T+hKOm4uYJUUoxg4drBCfLDyxO46OzhM0y6QtPA1Li6yVDIIsj26cIMRpSWMO6pSMc6tVTSG7r+CZ+okQJDuzr1WIVidisnqQJMgE9LqD8Ag1iXLrF9qXRCkLjyEQ== 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=zCtZi8vaoOW5F3VXQAVNZ0x0Te1tIv7kEIU1I+rjS88=; b=xMtWFIyd5Aln9YJrcWVziPOHzzknaytIxQP/ZF7kAQvrz1QPfEanirW8Kn2xzLWF+kZaPftk7Uv6UwCT1HVFNkIwvGaoI9PEsiRozHpbYmLLjhwJTNFjuzd00mlbck561VitFI91yXfLk5h75dsPfhudPteAfD+dWOBIBGc+5fecnufubCTXEbHe+5WTg/BulInNA1EloGJ+YLrZP2/WgVVhalqTM5LwUC1MhQmoPyMZ7nArT4LkGFZDRWypHefQlfq8MBWWLOVFsZQVyfJ58J0DPCeqy3JKPrqfYPzoXFOxiXVTbkR03asziB6Lw3y59kKjLsbUK6c6XiNWT2qRaw== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=zCtZi8vaoOW5F3VXQAVNZ0x0Te1tIv7kEIU1I+rjS88=; b=c/sEZR31VCjq4lMRGZxBtMDm3fqmtAb9yOiCq+5mUo5T3jMqgkdD/IX1/tMgxMrO9VYCIKsl/eqwuSNZwMjfVXoaDX7970HKYmsj1A2Eacb3HX3o7s/s4o14wTw5Iw1n1WecWiunUyIe5E9H5zlkYOk8pnaEB7rX0A8L933maFc= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO2P265MB3263.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:156::7) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.13; Thu, 11 Jun 2026 16:28:23 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:23 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:04 +0100 Subject: [PATCH v4 02/20] rust: io: add missing safety requirement in `IoCapable` methods Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-2-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195301; l=3721; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=3aH7apFce79+fBGN0fdMkFZxI0uuMM4f7+WP97okgN0=; b=D8b+7BOfC/hKCdA9Z7KZv8hfdDCwKE2hOwsz52LTzcF7tlkzdVjoTTLUT1YkZn+3yj0N7EQCc lRxBy6oAaPAAHFCeo12fiiiDuuexMRvNDfBdsQx9xMZYUqKZWgc1xaA X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO2P265MB3263:EE_ X-MS-Office365-Filtering-Correlation-Id: 8c6648e6-27cd-4028-07d0-08dec7d6753d X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|10070799003|1800799024|7416014|376014|366016|23010399003|18002099003|22082099003|921020|5023799004|6133799003|56012099006; X-Microsoft-Antispam-Message-Info: dlMc24V4KaZbgwK3tS3uDxgn5jQV3F3k05WVWNU+fq/71EEiVimBQfJf/d37YyQf+AgXVbmPhMOvDrYVVahqyrmKMi/hmUXX2m1GJGYlAGPANknuz2wzKtIrBcKNHMjJQdHzAH1/9B+Xzvjhp0hugqvdeFoMeZrrC8MVzTvZhFfUi27Qnc8wrGRk6MBdmOqmIWBj5CtQqf8RLwBXMOwLMhCOcB2lgyLYLLxtQD375SkbySw5+5YvGMxhABfV+Wf+urMbFS39eAdbetNKhAPmQA5z2WAalWr0JC5oR8xyaHOyp2XaRIHt8EzTxuioJ6V5O9wN2VrWX68RVDYJxfWvk7LOrvsGugdO3uVIuHLgJBk99WuO25yaOU4Jn077t4rsUdN3qaSM/rUPjoSDjKRRES77Nyg2cocRom/iKIJYtTrY1DfBK+iClxpRYYPBdsyq491uP1LNbjx11eTWrcj7oc00r2R1A2aKm6i+ADxWXRYHtjKE4KPW1rSbuCaa+Kvqu1xGA3/hhBjdsJ6aBb9pu+5Bu78i824grDENMnSv6vIaa1/8J0eFy8U9yrdUb6VE7tvIpm2ZbMIbzCXXsL8uuO7+K9haJJNaqo4MJ5tELuXCxbEl35jY6SNahjiNpj0ZzmIGGUbsEU+HI/t3Lw3MKyWfoFKz50uH0zF45Uz7/mtYbnlEVg/0dD6DjXgpPBg5hj1d3l7S0NsciCdT7+41wm+IvVFcbZ5R92zctTjlZm0= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(10070799003)(1800799024)(7416014)(376014)(366016)(23010399003)(18002099003)(22082099003)(921020)(5023799004)(6133799003)(56012099006);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?ZC9FNGl4UXNPY1k1R2VXV3plaEUzWXQvV0dBbitjakxPcWtCWFFhR2JRU0tR?= =?utf-8?B?Q0xtejFSSEY1a1Q1N0hvdTJocS8zOVNtcWVrQXR1YkZ3RUFXd0FjWWF3cWNo?= =?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S95UXBVNHAwcjVZdXE5dVJJMkZ2?= =?utf-8?B?MlpoQ3lvRytCUE11L04xYWJ0TU0vQUFTU3VUb1Bab1o4RUtZbmcvS3JJOTh4?= =?utf-8?B?SmFUZWd6VTArWGFmd1NWaVUzZXRlYldVam4rVk83cXFyQzhCcW1mcHhRL2dQ?= =?utf-8?B?VU5EYjRwNEJ5T3g2MzJRZjdWelBlRjFvTW1vQXlHRGo2VDVqVkkyT2VPNGs3?= =?utf-8?B?VE9NYXlpQnpyNkdUL2VWeTU0bkRxOU9CVjJsSXhPbjZjYnd1L3dIMDhRekly?= =?utf-8?B?T0Zab0tmMlBYSURRMTY1azJzdUpQenpoa1pweWt2UUN6MzZUcnYyT0JMTmU2?= =?utf-8?B?aVA0a2lBbnl1cnNvakxVYWl5UWNsdFhVTFR6Yjc1UDlab0xaVkc5S1RmS1o5?= =?utf-8?B?aEYyQVNKM1ZCaHlvZi9MY2lKenJyUGtiaWkwMXlUOGhoWjVPc1JaQT09?= X-OriginatorOrg: garyguo.net X-MS-Exchange-CrossTenant-Network-Message-Id: 8c6648e6-27cd-4028-07d0-08dec7d6753d X-MS-Exchange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:23.7935 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: 8+tcCxjcYAGT7NawrOWsBSZfkzUhHv5S9iNkcjUXfz3F3k/5/J7b5N5V2NnE5zIg5WAlNeF82AojqvZPdwv8uQ== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO2P265MB3263 The current safety comment on `io_read`/`io_write` does not cover the topic about alignment. Add it so it can be relied on by implementor of `IoCapable`. Expand the check `Io` by taking `self.addr()` into consideration when checking if `offset` is aligned. For the compile-time `io_addr_assert` check, check using the known minimum alignment of `IO::Target` and the accessed type. While at it, fix the alignment check to use `align_of` instead of `size_of`. The values match for all primitives (including u64, given that we do not provide u64 accessor on 32-bit platforms), but are not necessarily true for custom types. Signed-off-by: Gary Guo Suggested-by: Danilo Krummrich --- rust/kernel/io.rs | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index bef571dad6eb..fa9ae39ad9d2 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -196,13 +196,14 @@ pub fn maxsize(&self) -> usize { #[repr(transparent)] pub struct Mmio(MmioRaw); =20 -/// Checks whether an access of type `U` at the given `offset` +/// Checks whether an access of type `U` at the given `base` and the given= `offset` /// is valid within this region. +/// +/// The `base` is used for alignment checking only. This can be set to 0 t= o skip the check. #[inline] -const fn offset_valid(offset: usize, size: usize) -> bool { - let type_size =3D core::mem::size_of::(); - if let Some(end) =3D offset.checked_add(type_size) { - end <=3D size && offset % type_size =3D=3D 0 +const fn offset_valid(base: usize, offset: usize, size: usize) -> bool { + if let Some(end) =3D offset.checked_add(size_of::()) { + end <=3D size && (base.wrapping_add(offset) % align_of::() =3D= =3D 0) } else { false } @@ -221,14 +222,16 @@ pub trait IoCapable { /// /// # Safety /// - /// The range `[address..address + size_of::()]` must be within the= bounds of `Self`. + /// - The range `[address..address + size_of::()]` must be within t= he bounds of `Self`. + /// - `address` must be aligned. unsafe fn io_read(&self, address: usize) -> T; =20 /// Performs an I/O write of `value` at `address`. /// /// # Safety /// - /// The range `[address..address + size_of::()]` must be within the= bounds of `Self`. + /// - The range `[address..address + size_of::()]` must be within t= he bounds of `Self`. + /// - `address` must be aligned. unsafe fn io_write(&self, value: T, address: usize); } =20 @@ -310,7 +313,11 @@ pub trait Io { // Always inline to optimize out error path of `build_assert`. #[inline(always)] fn io_addr_assert(&self, offset: usize) -> usize { - build_assert!(offset_valid::(offset, Self::Target::MIN_SIZE)); + // We cannot check alignment with `offset_valid` using `self.addr(= )`. So set 0 for it and + // ensure alignment by checking that the alignment of `U` is small= er or equal to the + // alignment of `Self::Target`. + const_assert!(Alignment::of::().as_usize() <=3D Self::Target::M= IN_ALIGN.as_usize()); + build_assert!(offset_valid::(0, offset, Self::Target::MIN_SIZE)= ); =20 self.addr() + offset } @@ -319,7 +326,7 @@ fn io_addr_assert(&self, offset: usize) -> usize { /// performing runtime bound checks. #[inline] fn io_addr(&self, offset: usize) -> Result { - if !offset_valid::(offset, self.maxsize()) { + if !offset_valid::(self.addr(), offset, self.maxsize()) { return Err(EINVAL); } =20 --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from CWXP265CU010.outbound.protection.outlook.com (mail-ukwestazon11022091.outbound.protection.outlook.com [52.101.101.91]) (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 450C643E9F9; Thu, 11 Jun 2026 16:28:37 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.101.91 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195320; cv=fail; b=Y0c6jHBt362F0EnZHPSkilUX9iLJkzNK8z/JqkDvE5ukEj1JXKzDJhOu7X28ivaAScwveunNGbcOKV/cFT/bjkWpv5/nbpFIoz4hBIHZCTSw4c+jR/oIwTlMLEgndBHaoF19RKJMbBiInGYO7xU53jKGGDuRVUQcJlE13zEFOE0= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195320; c=relaxed/simple; bh=m2abPIgZ6CghqZ+aAQw1cMwRAHP/vg/dHPFnI7W46lk=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=IbYVpuoGM7KYYTEOrk+KVmaji+2kpDeKBXM6DZxLgAeBzn9wGaYW/IuFPrDKO1ENUvPob1uq3ZXQHev0j617ooBQ1Bg7SbVGPBqiDoNZiqgkmSI7Gq/lCHLir8ra9L5YVdlBLHnnvf5dN33uxw1iiWudodDLmO0uPoSbhkwm+v0= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=FVQzuuiY; arc=fail smtp.client-ip=52.101.101.91 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="FVQzuuiY" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=G2Q1mhaC98SskEesl7dCUq3skb3zBKSpgPImMqJOj8bPud6WOfay2IgYB/B+4OZiZPDtS90lJghZLKkgc9EGr5Cvv6OR937HFsG7z9TaTTgniWfKsxy78HRcfLu/3Syv8dzhtmmDQTVtB5axqigWGdCfC0OC2Nq8kKl1PozveA/6X5WkR4Z/+hyv6wrTluKES0fv4ON7TWr3o+STs+c8RbzoNOEvFk7SIEh4iw3xlkiCWSZkNocGJqpiuQ+AWWQmKrgSqF8XJqznvGawnkHG+2gZDYrENC5NesZH1U4Y7YjswX6vXh42EvGnJSSnZWgh89etaiMBXHGIsBomXee4lQ== 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=5aB7+V4PpNFVng659EBSbn8C1kIck9PoJQ0ssacoBk4=; b=UfaxJC6UTebMaC58pQpdARDzmPj6ig9JvmvmT8wmzmx9eM9hEC2s5ynKSJKid8DVV5rn2mE3s2I4oHt4iZObQjDt/mHs9ilpuTF0mnSoRgfk2ndSO4+fjl39lGb6mzGCw9doftW8vrW2Tm+/u24huAc8d502L/fkrk4X9MaPxvB9O6QWkRWaL+iwV2CXZrOe/qCPVeAdLLAKPHSUWXITqMqNLFMuwukTMcMKgp9zaWbp8ni9oKU3WYdQklcHhFLnXNnmpETYzzwY8TSI2ChIGOjFux6ffF/ittdAT8w9+3xsRawZSsPjYZ1HdgrKlKF7ZukqKQa+gYwDGOvmwQk0Xg== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=5aB7+V4PpNFVng659EBSbn8C1kIck9PoJQ0ssacoBk4=; b=FVQzuuiYhUWnLWVb+c6geYB74y/fiKLdAsfljr6gL575/wmg+fWvrlmD9Q0wzKUlXYuubh/Kdj+T6zt1trlVMLVcyb7MQFjDdTAtgXl9+GmZmX5Vb+zIbELvCOwzn9KUoxSuUrSGATluVJCuHOwsP53iEgYTkO5tHhL+ExjCFjs= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO2P265MB3263.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:156::7) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.13; Thu, 11 Jun 2026 16:28:24 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:24 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:05 +0100 Subject: [PATCH v4 03/20] rust: io: restrict untyped IO access and `register!` to `Region` Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-3-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195301; l=13424; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=m2abPIgZ6CghqZ+aAQw1cMwRAHP/vg/dHPFnI7W46lk=; b=E3vwb+pYw4gMGFfXfia7vl/heUsfCI4bd0lGSWgEszcov236tU9FJzMeTZLRn7FGzoHz546Sn 4pLfhwfCewvD+rCaOZFXQTESnSEkwHvfAYtnk05/y0SnrNQoqpu4z/u X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO2P265MB3263:EE_ X-MS-Office365-Filtering-Correlation-Id: a3ad979d-a615-4c23-31e9-08dec7d6759a X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|10070799003|1800799024|7416014|376014|366016|23010399003|18002099003|22082099003|921020|5023799004|6133799003|56012099006; X-Microsoft-Antispam-Message-Info: VacDnDYbnl88uTwclzXsYy7oNLi5D7SQZjRb1Wc4zxUmmOymG8I/W8YK31tJ/qgsalbsg0GU8gZ2IUODDUwGa53YUlNumzlZw19Vuu1XEo4OdTeqoQ353z6rXjfcY0HxBCyIza1SNzYS2hQpCxPRr3JwC77RG/taOtsJdiIwQ7nzxoiVzWvoNFrXK0WZcdnVRHCnQkdA4uBHxqFQMjxckHmBFz8iHmqk2AO/ICTLpRsYP13AplriYZfyenZAjBqkAOdhLAMt+MNv+DxNrSfHgc/5ZckCF/v+VL0+456KzYErGnzjGnTxlUA5JjboN9qCJ1XJXSBrTcwjjPVeUyI7H6st0/RvY7HvIxC3OMQg8OYigENB+v73AwYXP0dSIupUz1p106GRfMe1l5S1rqpDdhGAWFtUrMUHgS7/NDqnHX/eADr7917TicbztjNVEwfkd4sPHdIIKxQWTd+MY7JH74JudHHDn2wt/LTLUdHy+VupsMxmBWqtnXqzU29Lj792j6um2CBKvyKfoFuFupTOYp1wUtQgE3G3X70orAgEJ2PPIfDnZ23l26G7HcQT8sYaocbSsL2r29dC6pRYdClvtKv7B6Mxcxs26uJRdOc2dF1dpcsISCni7OSipRxBgVPFKXy4KYl4jO8l8zi+VmRY1oUafiEfr21+L/1JISToclgmAG5sn/EIy3cZAb30u+NQL3rPvkX07yj3995vgUEH1R6pdldGFr/8GKfsPMfTohHTk9Ou/wQBqMMjSRguI8RD X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(10070799003)(1800799024)(7416014)(376014)(366016)(23010399003)(18002099003)(22082099003)(921020)(5023799004)(6133799003)(56012099006);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?My9sYjhIaTNjbVRqVlZEQXFmN0V1S1hwUHJ3QjRMUVFhZU9GK2Q2QnpYMWIv?= =?utf-8?B?OVBSRDFTSmJ6OEhvNS9pVnQ5SXBoUjJxT1dxQ0xCZjVhdVR2bG5HbGtyRUhU?= =?utf-8?B?Tng5RU1nSm9qaUhMNXJQa2R6VmV5OEE3eGM3TVA3bWlyUllWeDIzRUZKZG9k?= =?utf-8?B?MFJFL29BcnRmZ1NTZFdZK25Ga2l3c3lFbC8yR0t0L2ZVQ1oxU25SRTZTRTVD?= =?utf-8?B?UXQ5WmtwSkxYbjJ1MlJ3SVBYR0k5aVhIK2hEU2tab2VITFB1ckdMeWg3NXFt?= =?utf-8?B?MXVuNDdpS0Ftc0YyWUgvbHMwRUhMUXdsTUFlWWpNejZ0ZWpQWWswQ3l4WXUw?= =?utf-8?B?dlI3dXEvUjYwajFLbldVYXhVTlNQMitQNURxM0pSdE1tMmk2MWt4cXhGWUFK?= =?utf-8?B?WVcyMUg1bmV0KzYzZjBnczVPcmZqaDBKUEdjUlRwaFlRYlI4YWJYOTNpNk8z?= =?utf-8?B?czNVOSsyQVFublFGQllIMlFxTW8rODFsNlpYQWJ2MUdDN0hxY2NjQTdsOG8x?= =?utf-8?B?eGtQVVQ5NC96SDZHbDUzNjAzWGNoT2NHNERQNEZrNW00SGtiTGVnSitFVGpu?= =?utf-8?B?UjZ2UU5wYTJBS3Roa3R0UH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ange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:24.4036 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: QpnLDvngK4V7JVd7MiMjqAG6uCNEq87+PVh930STEgEfZXhm+d4cRVC5XLJmcS3B2bU9JA/i/CQRfnmIzFyzsw== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO2P265MB3263 Currently the `Io` trait exposes a bunch of untyped IO accesses, but if the `Io` region itself is typed, then it might be weird to have let io: Mmio =3D /* ... */; io.read8(1); while not unsound, it is surely strange. Thus, restrict the untyped methods and also the register macro to `Region` type only. Implement it by adding a generic type to `IoLoc` indicating allowed base types. This also paves the way to add typed register blocks in the future; for example, we could use this mechanism to block driver A's `register!()` generated macro from being used on driver B's MMIO. The same mechanism could be used for relative IO registers. These are future opportunities, and for now restrict everything to require `IoLoc, _>`. Suggested-by: Alexandre Courbot Link: https://lore.kernel.org/rust-for-linux/DHLB3RO3OSF5.2R7F27U99BKLN@nvi= dia.com/ Signed-off-by: Gary Guo Reviewed-by: Alexandre Courbot Suggested-by: Danilo Krummrich --- rust/kernel/io.rs | 49 +++++++++++++++++++++++++++++++-----------= ---- rust/kernel/io/register.rs | 21 +++++++++++--------- 2 files changed, 45 insertions(+), 25 deletions(-) diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index fa9ae39ad9d2..38281636b4da 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -244,15 +244,16 @@ pub trait IoCapable { /// (for primitive types like [`u32`]) and typed ones (like those generate= d by the [`register!`] /// macro). /// -/// An `IoLoc` carries three pieces of information: +/// An `IoLoc` carries the following pieces of information: /// +/// - The valid `Base` to operate on. For most registers, this should be [= `Region`]. /// - 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 { +pub trait IoLoc { /// Size ([`u8`], [`u16`], etc) of the I/O performed on the returned [= `offset`](IoLoc::offset). type IoType: Into + From; =20 @@ -260,12 +261,12 @@ pub trait IoLoc { fn offset(self) -> usize; } =20 -/// Implements [`IoLoc<$ty>`] for [`usize`], allowing [`usize`] to be used= as a parameter of -/// [`Io::read`] and [`Io::write`]. +/// Implements [`IoLoc, $ty>`] for [`usize`], allowing [`usiz= e`] to be used as a +/// parameter of [`Io::read`] and [`Io::write`]. macro_rules! impl_usize_ioloc { ($($ty:ty),*) =3D> { $( - impl IoLoc<$ty> for usize { + impl IoLoc, $ty> for usize { type IoType =3D $ty; =20 #[inline(always)] @@ -339,6 +340,7 @@ fn io_addr(&self, offset: usize) -> Result { #[inline(always)] fn try_read8(&self, offset: usize) -> Result where + usize: IoLoc, Self: IoCapable, { self.try_read(offset) @@ -348,6 +350,7 @@ fn try_read8(&self, offset: usize) -> Result #[inline(always)] fn try_read16(&self, offset: usize) -> Result where + usize: IoLoc, Self: IoCapable, { self.try_read(offset) @@ -357,6 +360,7 @@ fn try_read16(&self, offset: usize) -> Result #[inline(always)] fn try_read32(&self, offset: usize) -> Result where + usize: IoLoc, Self: IoCapable, { self.try_read(offset) @@ -366,6 +370,7 @@ fn try_read32(&self, offset: usize) -> Result #[inline(always)] fn try_read64(&self, offset: usize) -> Result where + usize: IoLoc, Self: IoCapable, { self.try_read(offset) @@ -375,6 +380,7 @@ fn try_read64(&self, offset: usize) -> Result #[inline(always)] fn try_write8(&self, value: u8, offset: usize) -> Result where + usize: IoLoc, Self: IoCapable, { self.try_write(offset, value) @@ -384,6 +390,7 @@ fn try_write8(&self, value: u8, offset: usize) -> Result #[inline(always)] fn try_write16(&self, value: u16, offset: usize) -> Result where + usize: IoLoc, Self: IoCapable, { self.try_write(offset, value) @@ -393,6 +400,7 @@ fn try_write16(&self, value: u16, offset: usize) -> Res= ult #[inline(always)] fn try_write32(&self, value: u32, offset: usize) -> Result where + usize: IoLoc, Self: IoCapable, { self.try_write(offset, value) @@ -402,6 +410,7 @@ fn try_write32(&self, value: u32, offset: usize) -> Res= ult #[inline(always)] fn try_write64(&self, value: u64, offset: usize) -> Result where + usize: IoLoc, Self: IoCapable, { self.try_write(offset, value) @@ -411,6 +420,7 @@ fn try_write64(&self, value: u64, offset: usize) -> Res= ult #[inline(always)] fn read8(&self, offset: usize) -> u8 where + usize: IoLoc, Self: IoCapable, { self.read(offset) @@ -420,6 +430,7 @@ fn read8(&self, offset: usize) -> u8 #[inline(always)] fn read16(&self, offset: usize) -> u16 where + usize: IoLoc, Self: IoCapable, { self.read(offset) @@ -429,6 +440,7 @@ fn read16(&self, offset: usize) -> u16 #[inline(always)] fn read32(&self, offset: usize) -> u32 where + usize: IoLoc, Self: IoCapable, { self.read(offset) @@ -438,6 +450,7 @@ fn read32(&self, offset: usize) -> u32 #[inline(always)] fn read64(&self, offset: usize) -> u64 where + usize: IoLoc, Self: IoCapable, { self.read(offset) @@ -447,6 +460,7 @@ fn read64(&self, offset: usize) -> u64 #[inline(always)] fn write8(&self, value: u8, offset: usize) where + usize: IoLoc, Self: IoCapable, { self.write(offset, value) @@ -456,6 +470,7 @@ fn write8(&self, value: u8, offset: usize) #[inline(always)] fn write16(&self, value: u16, offset: usize) where + usize: IoLoc, Self: IoCapable, { self.write(offset, value) @@ -465,6 +480,7 @@ fn write16(&self, value: u16, offset: usize) #[inline(always)] fn write32(&self, value: u32, offset: usize) where + usize: IoLoc, Self: IoCapable, { self.write(offset, value) @@ -474,6 +490,7 @@ fn write32(&self, value: u32, offset: usize) #[inline(always)] fn write64(&self, value: u64, offset: usize) where + usize: IoLoc, Self: IoCapable, { self.write(offset, value) @@ -504,7 +521,7 @@ fn write64(&self, value: u64, offset: usize) #[inline(always)] fn try_read(&self, location: L) -> Result where - L: IoLoc, + L: IoLoc, Self: IoCapable, { let address =3D self.io_addr::(location.offset())?; @@ -538,7 +555,7 @@ fn try_read(&self, location: L) -> Result #[inline(always)] fn try_write(&self, location: L, value: T) -> Result where - L: IoLoc, + L: IoLoc, Self: IoCapable, { let address =3D self.io_addr::(location.offset())?; @@ -584,8 +601,8 @@ fn try_write(&self, location: L, value: T) -> Res= ult #[inline(always)] fn try_write_reg(&self, value: V) -> Result where - L: IoLoc, - V: LocatedRegister, + L: IoLoc, + V: LocatedRegister, Self: IoCapable, { let (location, value) =3D value.into_io_op(); @@ -617,7 +634,7 @@ fn try_write_reg(&self, value: V) -> Result #[inline(always)] fn try_update(&self, location: L, f: F) -> Result where - L: IoLoc, + L: IoLoc, Self: IoCapable, F: FnOnce(T) -> T, { @@ -656,7 +673,7 @@ fn try_update(&self, location: L, f: F) -> Res= ult #[inline(always)] fn read(&self, location: L) -> T where - L: IoLoc, + L: IoLoc, Self: IoCapable, { let address =3D self.io_addr_assert::(location.offset()= ); @@ -688,7 +705,7 @@ fn read(&self, location: L) -> T #[inline(always)] fn write(&self, location: L, value: T) where - L: IoLoc, + L: IoLoc, Self: IoCapable, { let address =3D self.io_addr_assert::(location.offset()= ); @@ -731,8 +748,8 @@ fn write(&self, location: L, value: T) #[inline(always)] fn write_reg(&self, value: V) where - L: IoLoc, - V: LocatedRegister, + L: IoLoc, + V: LocatedRegister, Self: IoCapable, { let (location, value) =3D value.into_io_op(); @@ -764,8 +781,8 @@ fn write_reg(&self, value: V) #[inline(always)] fn update(&self, location: L, f: F) where - L: IoLoc, - Self: IoCapable + Sized, + L: IoLoc, + Self: IoCapable, F: FnOnce(T) -> T, { let address =3D self.io_addr_assert::(location.offset()= ); diff --git a/rust/kernel/io/register.rs b/rust/kernel/io/register.rs index f924c7c7c1db..64fff9193a13 100644 --- a/rust/kernel/io/register.rs +++ b/rust/kernel/io/register.rs @@ -113,6 +113,8 @@ io::IoLoc, // }; =20 +use super::Region; + /// Trait implemented by all registers. pub trait Register: Sized { /// Backing primitive type of the register. @@ -129,7 +131,7 @@ pub trait FixedRegister: Register {} =20 /// Allows `()` to be used as the `location` parameter of [`Io::write`](su= per::Io::write) when /// passing a [`FixedRegister`] value. -impl IoLoc for () +impl IoLoc, T> for () where T: FixedRegister, { @@ -143,7 +145,7 @@ fn offset(self) -> usize { =20 /// A [`FixedRegister`] carries its location in its type. Thus `FixedRegis= ter` values can be used /// as an [`IoLoc`]. -impl IoLoc for T +impl IoLoc, T> for T where T: FixedRegister, { @@ -168,7 +170,7 @@ pub const fn new() -> Self { } } =20 -impl IoLoc for FixedRegisterLoc +impl IoLoc, T> for FixedRegisterLoc where T: FixedRegister, { @@ -239,7 +241,8 @@ const fn offset(self) -> usize { } } =20 -impl IoLoc for RelativeRegisterLoc +// FIXME: Make use of `Base` type parameter of `Region` directly. +impl IoLoc, T> for RelativeRegisterL= oc where T: RelativeRegister, B: RegisterBase + ?Sized, @@ -283,7 +286,7 @@ pub fn try_new(idx: usize) -> Option { } } =20 -impl IoLoc for RegisterArrayLoc +impl IoLoc, T> for RegisterArrayLoc where T: RegisterArray, { @@ -370,7 +373,7 @@ pub fn try_at(self, idx: usize) -> Option> { } } =20 -impl IoLoc for RelativeRegisterArrayLoc +impl IoLoc, T> for RelativeRegisterA= rrayLoc where T: RelativeRegisterArray, B: RegisterBase + ?Sized, @@ -387,18 +390,18 @@ fn offset(self) -> usize { /// which to write it. /// /// Implementors can be used with [`Io::write_reg`](super::Io::write_reg). -pub trait LocatedRegister { +pub trait LocatedRegister { /// Register value to write. type Value: Register; /// Full location information at which to write the value. - type Location: IoLoc; + type Location: IoLoc; =20 /// Consumes `self` and returns a `(location, value)` tuple describing= a valid I/O write /// operation. fn into_io_op(self) -> (Self::Location, Self::Value); } =20 -impl LocatedRegister for T +impl LocatedRegister> for T where T: FixedRegister, { --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from LO0P265CU003.outbound.protection.outlook.com (mail-uksouthazon11022092.outbound.protection.outlook.com [52.101.96.92]) (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 A40BD43D518; Thu, 11 Jun 2026 16:28:36 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.96.92 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195319; cv=fail; b=dqxicXqgARM3TxbR5ELLPZjcLDdkysQp3Vo/ThrGz6IqJ7OEGQMrfKDsEqyqmyAbFb3xtV1RKPKfh0BKwUc1Wv1iWWaY85ut/BKGaidPfBFL6wUq4dC4EMpqfcoQdE4pycRaZdRleJAV04yH5qyAf9sznn15ffyuKK5IM6IJEmg= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195319; c=relaxed/simple; bh=zAUmlpx7qRmpak2aPShtkQ1ta2dTWYwEkvis5uE7440=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=S9Z0CAbptBPaO3XYwc9GZxKq5zS2G/BwIm/gAYKe1RmwuPBABOW1UV1CN/duGa/+DYID/UpXNiVUXNz58u+EuU2iv/TfDZ7yH9CdKRbRAPiAWoK7bqfh2ApjAKGr3qyoYTE2aAP37h+znfHZrDWxR4AuGC+70RfyiSIu2vDEOII= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=0iqTK8y3; arc=fail smtp.client-ip=52.101.96.92 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="0iqTK8y3" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=rl1FTEe0HOeBzXIMp8qfgDAfy8b3tIz0YzQchSHa2I9I43xEtE/yXrJNhBYI4NaHtYZzslms5vj8wFuEQU8MXkrzPyCKqzuzIC3yMY08vUtcdMtc0wHdh7Xll7lph6oUjyP0pvkeNS69ebYaPEAX4Mf2TdmhCm0F5DKVUPKDlVqfLRjPdRA+5bcrj/qi1HpEwu+6fleF1F7rdIY0xIIR2lRfy01U8tZZWw6VONClARpLhviVfUAExCXZl8+XknM36sNX9DV5n6ol6+eNKQoi7N+07dyXOvX+h6j7INjYcNJpwM3rUZjyvaZVyEmb2Ecok5YqL1g6P8ERh+BxBneE9w== 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=Pgr7srKWqQ5y9Ad7bmawsaDw59mKVPoPKoj87/Fi+4E=; b=wAtPQU9RYu09rVVwPArvh9Z+ErCWLKm/xKVSew1AbzQiki+JkyqVGj7JqheEhplQJx1MGnYq9Lo35f9Zx31hRYsAt5Fd7RupDxb2nqg9RUSYSS5DQJ/KEP0S8tSx4bbU1MT9ANz+paXVhD1QFa4FsZZQEaNeNzjjXDcQu3w69XHf9KKX3qedhsUaaBvlhHfzOXTEVkSmc2RsqnEQaBuoH6t3VY1VHPWY8kBhs3rKOX/UYF9At/HpDPM8bT7tKW61/e+kKk0F5lA4lH0YhRUTGV022D8sqde4BFZzKk0LncMZwEnAtspNOT5tOpEDJu0hMoUAaSU63Uf4wBbH/4J1MA== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=Pgr7srKWqQ5y9Ad7bmawsaDw59mKVPoPKoj87/Fi+4E=; b=0iqTK8y3Bnep6JDL13XaFL/1NCOS0w8iTtKiInMJlkzQVHGC310qCODKq8yJgmXhb1SpirHN1Db4ClWglLg2Gu7hhAiJeKLRECdctMnT9GfscsJMVQHGp+SFwKxmxS+tcERYs5l7bU5ntCgYHg1bKR2AGGqKYtsp0fEfpzt3DYY= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO2P265MB3263.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:156::7) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.13; Thu, 11 Jun 2026 16:28:25 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:25 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:06 +0100 Subject: [PATCH v4 04/20] rust: io: implement `Io` on reference types instead Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-4-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195301; l=16076; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=zAUmlpx7qRmpak2aPShtkQ1ta2dTWYwEkvis5uE7440=; b=+MsbIQhEGGJURZCK0Jdt0IdZEkCam4LJw+6+gxZeEHa5GEZm9I2OV4qtae3ko3I4Q/sw+OoMO RfLW9564I9YCxffBesGd2Z1SgSJqzzky4lE7wjDIOqa2A3Fl64Af1U1 X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO2P265MB3263:EE_ X-MS-Office365-Filtering-Correlation-Id: 825ffc85-bbda-4c94-a41e-08dec7d675f5 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|10070799003|1800799024|7416014|376014|366016|23010399003|18002099003|22082099003|921020|5023799004|6133799003|56012099006; X-Microsoft-Antispam-Message-Info: T37cbllAk+3ZfVwhUS9lx4eI5L2wM1cjx1E/lzogHSV5IYdJG1GTLBWbr+iawZuDrmdcrJ+umdg0C7f1Z22qYIsS3JrprLOuPkIsaujMWtSyp8ETBPjjnGt6p1O8RDQa342jnzndaGPvAJw2OZVbua/J+DlIu6ZYECEh5hsxCfCfHM+kKJOqIqii2lmXN4LsuJO/DgbBABAeqp2MSpUTMRSO1tcMVZYF4PURnwldUqzS4bj45tlSiRF5wC67QFF9RXYuJk5Wz0QOVcLxCw+toHjW9tHC/sLq+NH8z+r82ACrW4kKnnqpI2lp7j/UuG7nhEYZ1t4Uk0ieGyUGxtGEk4NHtZOxy6IPFax/i95CGPTHxkdiPOd6Rcvx9Pma4HpKoXAGCwb6IAMMWi2NGdMj3yI7ao5/yHVhksEULvbex9pGdUBPiV7SGReNDdiGZoQUbULH1nyLcvYyXXhb9v2pzRZnIYH8O1OGW+8g3WlaGyHGNEkH6TY7iu56JScG8RlL8YkX24QGUy6vXl44rchE/L1Tc7Oi3WAzQee2JN0ym9ydxbKLFlRg+rFbJaytann0BIttYafH2PBuzkoM3jaib5yCAP/M/C3qE9pkt6Hk665CMYeNNJJgdQAJs1VFC18LnzzPXVgl+J8ZPkJ5ppFcWsfVwZqW6k/K7TH8tP6G7ep8x/Apij1jYOsC5ccD5YJBoVJCkjtrS9POHayc5IS1bdqK9DDlSugUNZccO18jNho= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(10070799003)(1800799024)(7416014)(376014)(366016)(23010399003)(18002099003)(22082099003)(921020)(5023799004)(6133799003)(56012099006);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?bjdhQXYyTXJjMHRHM3N5ZG9PZ3NSczR5WFN1c2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8?B?SGZDS253dmFmVlhaOEE4S2Z6ZmMzL1QzdzdpK0FiSDl5Wk96ZGhhc0hyQ0N3?= =?utf-8?B?azI0YjJDTXU4N2M5M2s5ejJWSGxPenRDZDluQ3BTeStnMVB6b00rL3hwU25G?= =?utf-8?B?dXhEQTJRdXEyWlpRa3NHWUJjQzNvQzh4ZzExRU51cUNDdXlTbUhkRGs2MkJZ?= =?utf-8?B?U20vY1FoTXJZc1VwVjdITjcxZHBVSU5jclZDYnJ0K3dRUTFZT1dvNUZhbDFK?= =?utf-8?B?Z2hicjllY3AvZTY0d2U1OXBBcjU3V0hSZndwZTg4MDlDU0FzYWc3WWdrejBI?= =?utf-8?B?by96NmZZR2hDUVVTUUhsaWlMM1gxVGR6c05zeWJIZFEvTHNXVlpyelNSMG93?= =?utf-8?B?OTZqcjNpRjBSNWJKS2lqU0pCamVVUks0REFWOGRKYmRkbTl2Y25BWlB0OThw?= =?utf-8?B?cHJvVmFjQmk0N1Jpb2NRU2NEOFBuSk9LWWlvRURrTHZqVXlVRXJtTmp4OUxm?= =?utf-8?B?Y3BMVm5LVGJlUlArSWtGekhLQ1RrYW45ek9OY1Q2YnIweXVKVzNaUT09?= X-OriginatorOrg: garyguo.net X-MS-Exchange-CrossTenant-Network-Message-Id: 825ffc85-bbda-4c94-a41e-08dec7d675f5 X-MS-Exchange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:25.0241 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: chrt3XK1AfK20BKXvgk1KHGhXjgzdWLzDpEKiCsmgthejY1M8V8gToNuU2REKjC2ebmFwQHesrck7807ZiP8MQ== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO2P265MB3263 Currently, `Io` is implemented on owned I/O objects (e.g. `Bar`). This is going to change with I/O projections, as then `Io` need to work both for owned objects and views of them. Views are themselves reference-like (however they obviously cannot be references, because they belong to a different address space). To faciliate the change, change `Io` to be implemented on reference types for the owned I/O objects, and make methods take `self` instead of `&self`. When I/O views are implemented, we can then naturally implement `Io` for these objects. Signed-off-by: Gary Guo Reviewed-by: Alexandre Courbot Suggested-by: Danilo Krummrich --- rust/kernel/io.rs | 80 +++++++++++++++++++++++++----------------------= ---- rust/kernel/pci/io.rs | 12 ++++---- 2 files changed, 46 insertions(+), 46 deletions(-) diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index 38281636b4da..3b478dcf10f9 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -224,7 +224,7 @@ pub trait IoCapable { /// /// - The range `[address..address + size_of::()]` must be within t= he bounds of `Self`. /// - `address` must be aligned. - unsafe fn io_read(&self, address: usize) -> T; + unsafe fn io_read(self, address: usize) -> T; =20 /// Performs an I/O write of `value` at `address`. /// @@ -232,7 +232,7 @@ pub trait IoCapable { /// /// - The range `[address..address + size_of::()]` must be within t= he bounds of `Self`. /// - `address` must be aligned. - unsafe fn io_write(&self, value: T, address: usize); + 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 @@ -299,21 +299,21 @@ fn offset(self) -> usize { /// /// For MMIO regions, all widths (u8, u16, u32, and u64 on 64-bit systems)= are typically /// supported. For PCI configuration space, u8, u16, and u32 are supported= but u64 is not. -pub trait Io { +pub trait Io: Copy { /// Type of this I/O region. For untyped regions, [`Region`] can be us= ed. type Target: ?Sized + KnownSize; =20 /// Returns the base address of this mapping. - fn addr(&self) -> usize; + fn addr(self) -> usize; =20 /// Returns the maximum size of this mapping. - fn maxsize(&self) -> usize; + fn maxsize(self) -> usize; =20 /// Returns the absolute I/O address for a given `offset`, /// performing compile-time bound checks. // Always inline to optimize out error path of `build_assert`. #[inline(always)] - fn io_addr_assert(&self, offset: usize) -> usize { + fn io_addr_assert(self, offset: usize) -> usize { // We cannot check alignment with `offset_valid` using `self.addr(= )`. So set 0 for it and // ensure alignment by checking that the alignment of `U` is small= er or equal to the // alignment of `Self::Target`. @@ -326,7 +326,7 @@ fn io_addr_assert(&self, offset: usize) -> usize { /// Returns the absolute I/O address for a given `offset`, /// performing runtime bound checks. #[inline] - fn io_addr(&self, offset: usize) -> Result { + fn io_addr(self, offset: usize) -> Result { if !offset_valid::(self.addr(), offset, self.maxsize()) { return Err(EINVAL); } @@ -338,7 +338,7 @@ fn io_addr(&self, offset: usize) -> Result { =20 /// Fallible 8-bit read with runtime bounds check. #[inline(always)] - fn try_read8(&self, offset: usize) -> Result + fn try_read8(self, offset: usize) -> Result where usize: IoLoc, Self: IoCapable, @@ -348,7 +348,7 @@ fn try_read8(&self, offset: usize) -> Result =20 /// Fallible 16-bit read with runtime bounds check. #[inline(always)] - fn try_read16(&self, offset: usize) -> Result + fn try_read16(self, offset: usize) -> Result where usize: IoLoc, Self: IoCapable, @@ -358,7 +358,7 @@ fn try_read16(&self, offset: usize) -> Result =20 /// Fallible 32-bit read with runtime bounds check. #[inline(always)] - fn try_read32(&self, offset: usize) -> Result + fn try_read32(self, offset: usize) -> Result where usize: IoLoc, Self: IoCapable, @@ -368,7 +368,7 @@ fn try_read32(&self, offset: usize) -> Result =20 /// Fallible 64-bit read with runtime bounds check. #[inline(always)] - fn try_read64(&self, offset: usize) -> Result + fn try_read64(self, offset: usize) -> Result where usize: IoLoc, Self: IoCapable, @@ -378,7 +378,7 @@ fn try_read64(&self, offset: usize) -> Result =20 /// Fallible 8-bit write with runtime bounds check. #[inline(always)] - fn try_write8(&self, value: u8, offset: usize) -> Result + fn try_write8(self, value: u8, offset: usize) -> Result where usize: IoLoc, Self: IoCapable, @@ -388,7 +388,7 @@ fn try_write8(&self, value: u8, offset: usize) -> Result =20 /// Fallible 16-bit write with runtime bounds check. #[inline(always)] - fn try_write16(&self, value: u16, offset: usize) -> Result + fn try_write16(self, value: u16, offset: usize) -> Result where usize: IoLoc, Self: IoCapable, @@ -398,7 +398,7 @@ fn try_write16(&self, value: u16, offset: usize) -> Res= ult =20 /// Fallible 32-bit write with runtime bounds check. #[inline(always)] - fn try_write32(&self, value: u32, offset: usize) -> Result + fn try_write32(self, value: u32, offset: usize) -> Result where usize: IoLoc, Self: IoCapable, @@ -408,7 +408,7 @@ fn try_write32(&self, value: u32, offset: usize) -> Res= ult =20 /// Fallible 64-bit write with runtime bounds check. #[inline(always)] - fn try_write64(&self, value: u64, offset: usize) -> Result + fn try_write64(self, value: u64, offset: usize) -> Result where usize: IoLoc, Self: IoCapable, @@ -418,7 +418,7 @@ fn try_write64(&self, value: u64, offset: usize) -> Res= ult =20 /// Infallible 8-bit read with compile-time bounds check. #[inline(always)] - fn read8(&self, offset: usize) -> u8 + fn read8(self, offset: usize) -> u8 where usize: IoLoc, Self: IoCapable, @@ -428,7 +428,7 @@ fn read8(&self, offset: usize) -> u8 =20 /// Infallible 16-bit read with compile-time bounds check. #[inline(always)] - fn read16(&self, offset: usize) -> u16 + fn read16(self, offset: usize) -> u16 where usize: IoLoc, Self: IoCapable, @@ -438,7 +438,7 @@ fn read16(&self, offset: usize) -> u16 =20 /// Infallible 32-bit read with compile-time bounds check. #[inline(always)] - fn read32(&self, offset: usize) -> u32 + fn read32(self, offset: usize) -> u32 where usize: IoLoc, Self: IoCapable, @@ -448,7 +448,7 @@ fn read32(&self, offset: usize) -> u32 =20 /// Infallible 64-bit read with compile-time bounds check. #[inline(always)] - fn read64(&self, offset: usize) -> u64 + fn read64(self, offset: usize) -> u64 where usize: IoLoc, Self: IoCapable, @@ -458,7 +458,7 @@ fn read64(&self, offset: usize) -> u64 =20 /// Infallible 8-bit write with compile-time bounds check. #[inline(always)] - fn write8(&self, value: u8, offset: usize) + fn write8(self, value: u8, offset: usize) where usize: IoLoc, Self: IoCapable, @@ -468,7 +468,7 @@ fn write8(&self, value: u8, offset: usize) =20 /// Infallible 16-bit write with compile-time bounds check. #[inline(always)] - fn write16(&self, value: u16, offset: usize) + fn write16(self, value: u16, offset: usize) where usize: IoLoc, Self: IoCapable, @@ -478,7 +478,7 @@ fn write16(&self, value: u16, offset: usize) =20 /// Infallible 32-bit write with compile-time bounds check. #[inline(always)] - fn write32(&self, value: u32, offset: usize) + fn write32(self, value: u32, offset: usize) where usize: IoLoc, Self: IoCapable, @@ -488,7 +488,7 @@ fn write32(&self, value: u32, offset: usize) =20 /// Infallible 64-bit write with compile-time bounds check. #[inline(always)] - fn write64(&self, value: u64, offset: usize) + fn write64(self, value: u64, offset: usize) where usize: IoLoc, Self: IoCapable, @@ -519,7 +519,7 @@ fn write64(&self, value: u64, offset: usize) /// } /// ``` #[inline(always)] - fn try_read(&self, location: L) -> Result + fn try_read(self, location: L) -> Result where L: IoLoc, Self: IoCapable, @@ -553,7 +553,7 @@ fn try_read(&self, location: L) -> Result /// } /// ``` #[inline(always)] - fn try_write(&self, location: L, value: T) -> Result + fn try_write(self, location: L, value: T) -> Result where L: IoLoc, Self: IoCapable, @@ -599,7 +599,7 @@ fn try_write(&self, location: L, value: T) -> Res= ult /// } /// ``` #[inline(always)] - fn try_write_reg(&self, value: V) -> Result + fn try_write_reg(self, value: V) -> Result where L: IoLoc, V: LocatedRegister, @@ -632,7 +632,7 @@ fn try_write_reg(&self, value: V) -> Result /// } /// ``` #[inline(always)] - fn try_update(&self, location: L, f: F) -> Result + fn try_update(self, location: L, f: F) -> Result where L: IoLoc, Self: IoCapable, @@ -671,7 +671,7 @@ fn try_update(&self, location: L, f: F) -> Res= ult /// } /// ``` #[inline(always)] - fn read(&self, location: L) -> T + fn read(self, location: L) -> T where L: IoLoc, Self: IoCapable, @@ -703,7 +703,7 @@ fn read(&self, location: L) -> T /// } /// ``` #[inline(always)] - fn write(&self, location: L, value: T) + fn write(self, location: L, value: T) where L: IoLoc, Self: IoCapable, @@ -746,7 +746,7 @@ fn write(&self, location: L, value: T) /// } /// ``` #[inline(always)] - fn write_reg(&self, value: V) + fn write_reg(self, value: V) where L: IoLoc, V: LocatedRegister, @@ -779,7 +779,7 @@ fn write_reg(&self, value: V) /// } /// ``` #[inline(always)] - fn update(&self, location: L, f: F) + fn update(self, location: L, f: F) where L: IoLoc, Self: IoCapable, @@ -800,13 +800,13 @@ fn update(&self, location: L, f: F) macro_rules! impl_mmio_io_capable { ($mmio:ident, $(#[$attr:meta])* $ty:ty, $read_fn:ident, $write_fn:iden= t) =3D> { $(#[$attr])* - impl IoCapable<$ty> for $mmio { - unsafe fn io_read(&self, address: usize) -> $ty { + impl IoCapable<$ty> for &$mmio { + unsafe fn io_read(self, address: usize) -> $ty { // SAFETY: By the trait invariant `address` is a valid add= ress for MMIO operations. unsafe { bindings::$read_fn(address as *const c_void) } } =20 - unsafe fn io_write(&self, value: $ty, address: usize) { + unsafe fn io_write(self, value: $ty, address: usize) { // SAFETY: By the trait invariant `address` is a valid add= ress for MMIO operations. unsafe { bindings::$write_fn(value, address as *mut c_void= ) } } @@ -827,18 +827,18 @@ unsafe fn io_write(&self, value: $ty, address: usize)= { writeq ); =20 -impl Io for Mmio { +impl<'a, const SIZE: usize> Io for &'a Mmio { type Target =3D Region; =20 /// Returns the base address of this mapping. #[inline] - fn addr(&self) -> usize { + fn addr(self) -> usize { self.0.addr() } =20 /// Returns the maximum size of this mapping. #[inline] - fn maxsize(&self) -> usize { + fn maxsize(self) -> usize { self.0.maxsize() } } @@ -865,16 +865,16 @@ pub unsafe fn from_raw(raw: &MmioRaw) -> &Self { #[repr(transparent)] pub struct RelaxedMmio(Mmio); =20 -impl Io for RelaxedMmio { +impl<'a, const SIZE: usize> Io for &'a RelaxedMmio { type Target =3D Region; =20 #[inline] - fn addr(&self) -> usize { + fn addr(self) -> usize { self.0.addr() } =20 #[inline] - fn maxsize(&self) -> usize { + fn maxsize(self) -> usize { self.0.maxsize() } } diff --git a/rust/kernel/pci/io.rs b/rust/kernel/pci/io.rs index b4996aa059d8..505305cd9b86 100644 --- a/rust/kernel/pci/io.rs +++ b/rust/kernel/pci/io.rs @@ -79,8 +79,8 @@ pub struct ConfigSpace<'a, S: ?Sized + ConfigSpaceKind = =3D Extended> { /// Implements [`IoCapable`] on [`ConfigSpace`] for `$ty` using `$read_fn`= and `$write_fn`. macro_rules! impl_config_space_io_capable { ($ty:ty, $read_fn:ident, $write_fn:ident) =3D> { - impl<'a, S: ?Sized + ConfigSpaceKind> IoCapable<$ty> for ConfigSpa= ce<'a, S> { - unsafe fn io_read(&self, address: usize) -> $ty { + impl<'a, S: ?Sized + ConfigSpaceKind> IoCapable<$ty> for &ConfigSp= ace<'a, S> { + unsafe fn io_read(self, address: usize) -> $ty { let mut val: $ty =3D 0; =20 // Return value from C function is ignored in infallible a= ccessors. @@ -94,7 +94,7 @@ unsafe fn io_read(&self, address: usize) -> $ty { val } =20 - unsafe fn io_write(&self, value: $ty, address: usize) { + unsafe fn io_write(self, value: $ty, address: usize) { // Return value from C function is ignored in infallible a= ccessors. let _ret =3D // SAFETY: By the type invariant `self.pdev` is a vali= d address. @@ -112,18 +112,18 @@ unsafe fn io_write(&self, value: $ty, address: usize)= { impl_config_space_io_capable!(u16, pci_read_config_word, pci_write_config_= word); impl_config_space_io_capable!(u32, pci_read_config_dword, pci_write_config= _dword); =20 -impl<'a, S: ?Sized + ConfigSpaceKind> Io for ConfigSpace<'a, S> { +impl<'a, S: ?Sized + ConfigSpaceKind> Io for &ConfigSpace<'a, S> { type Target =3D S; =20 /// Returns the base address of the I/O region. It is always 0 for con= figuration space. #[inline] - fn addr(&self) -> usize { + fn addr(self) -> usize { 0 } =20 /// Returns the maximum size of the configuration space. #[inline] - fn maxsize(&self) -> usize { + fn maxsize(self) -> usize { self.pdev.cfg_size().into_raw() } } --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from LO0P265CU003.outbound.protection.outlook.com (mail-uksouthazon11022092.outbound.protection.outlook.com [52.101.96.92]) (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 B32834508F2; Thu, 11 Jun 2026 16:28:39 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.96.92 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195322; cv=fail; b=QlXv5Hv5lbeVNhUC4SRAUQHIQisjjNEEXiGQB75h3d6AcNmw36sWsfuPN31zIXw52tWo95W2k9qAyNSVsSkm0kHwTYX4Z2yJab7B0SvYgkH8RPICnWPxQbSB8nCcmjEFkLxlIsgJZbqRqsqFXT35I4mhniGhC+q1r93MQ1lfIqg= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195322; c=relaxed/simple; bh=goWQJ0ThqV+Q3smjs/gu7WOWjqv2qJjkHt4GzWinuVo=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=Yv9QlEeRxQ8CJw9ktHyTVZwKh3EkJM6ELQkU40m5RxOI8DP/LWjPAA7f+5khP0TMlriTBaEzHVdhZwaz5tnXH+o9m3UZ0B/mDE6Wz5LI9lKmAfj0HcrquZhg6jhpKqKwQbwLTXmaJOdVil/+XLYWOGvnJSQp49yjKp0HUtKZ2Pw= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=oAKOcfzd; arc=fail smtp.client-ip=52.101.96.92 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="oAKOcfzd" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=iAFfTJO8ojylEH+hHlBZePjLCcE0eAxZeHsGoMSy3qidMjATdlVnpFrkofWCXI2OuQVcJeEgMgqZPJttYdPpbmHbiZcGXjm3/sBp3yCMHch00H4VCJ98r87dfwwHKz9dcO8TXmytWkvi+HkZbLZ1kfE3LdV91m1uICwzhmeoeSc6a/SIQrZz27NjRBcD7fqpTRPXcufCEtkhIIRT44l8/FDKIiEaKh3CWmMFOt7MJ/GhUZ3rGZH5xIgSrBuf6+28AHkseHraFNu769zWE6e5rUKqR1kUhtiGQXgg3qzJiN2Mzpt53NSPPlHMAa8eaWEozhUeZOLG24IrOUDt5+MPjQ== 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=yXhVRgl85wuRcvaMXiSEbAEkYhmJUzpAzdTGo9eVxqE=; b=ZodEbi7wKvuXJY19h6gLKy1lJS+Dp+bysCI96fpLtE04+L8lR9DtSq0B4dLdAVuOLj1A9/JT+IgCfrH0CTzrfUkjNuzAINgwfjgfx9onV0qz5va3YzMD34yTJ+9gOdPkNJaHcwxtGwBzLtBZ5wSCU5KmggC9SGZkITKpn5qD+w6OLiXPGkYXWNtzhBnu8xMoS0yFhK8IpCl0sA0wqiZ0xxIm7UpQFe/dOO9aAJBw6gznEUFr8v/w5mk1RMpB27hyESfZM5xewqrmYp4+f83ZKfdTtlqVfYC4dbtVxQGqO6pE6Yv1YMIfG2SC83ZfBFz0mfziri0N8UilX9G7OxS+fg== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=yXhVRgl85wuRcvaMXiSEbAEkYhmJUzpAzdTGo9eVxqE=; b=oAKOcfzdTt5MR7PkQ7mEtLa2T5KrJU4jxjctg1zF2/1x7Hio9xXhm9MiOeQG7mvZd9iElMGNDTqVNppzBFmXR3Q9VQMLT0CwsNmzTTFR4iUHTkIsEbMHa3sLDn/H+a95F1nACPoTKbjIGW98OnunSnQUojU2XPLHi5pq6WddVAs= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO2P265MB3263.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:156::7) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.13; Thu, 11 Jun 2026 16:28:25 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:25 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:07 +0100 Subject: [PATCH v4 05/20] rust: io: generalize `MmioRaw` to pointer to arbitrary type Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-5-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195301; l=7828; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=goWQJ0ThqV+Q3smjs/gu7WOWjqv2qJjkHt4GzWinuVo=; b=k9YiAb9v4cjRQbAUWlvlUCXKL93Pd9Fo67RJvaIPB6uOa0CnkJysKPFRbF7Lm2L9T7iV7wP3S t7IRyG0IPMlDqEbf2n1VPQf/9js1fMom0hoZQMUQmKKRwml38WmrMkD X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO2P265MB3263:EE_ X-MS-Office365-Filtering-Correlation-Id: b99ee732-e639-48e0-68f0-08dec7d67654 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|10070799003|1800799024|7416014|376014|366016|23010399003|18002099003|22082099003|921020|6133799003|56012099006; X-Microsoft-Antispam-Message-Info: 7r6m24igwOsLg45G6pno7N/Khc4SYROsYj3MCHe0eyryxioFdhI8YH2zda6d4DA+Yhdz3iYIq+JPCPmBlXfJ886fPbPDcr1wOemgcZ8kl+mzD7NV3v+V+SB/667dQFBRuAD0V3VaWCBYtAey3q/AdO3ny2kQ0S7CIihHqrrHQuSA8C8WOXyT3znC22B1JKUhJRst8+JJrvCe6U6BJVX78YgGyCz/3hsbKZyBPI7izahPT47jKAe5eeFWz6ePj3+bKrIR3pFZ4/2qcZVCbYPTeVsBAH5Io4aUgsc9qmUuDUaYUdMHeNNjgD9yvYVt4bKHBF0f7yj03ORpB44ecN+HyW3jl5YAXaFqadjJZ/jialmANCSeA1lpwrAZ5OPu47pleK4psZs7cEn98ICZcTR/nIbECD9sEzXTdQg1NZiN9zjBIG3dpnMaO2IdO/gEr6lyc5GZhyCccOzMrCsL85jSWvJBj560dt23w1YXDR/vudhMFa+p9X/Ms9T8q+TRBgUmavFS9BzJa3atvgLCz0aPhC20Tmth+N1yhovUowkI872U+KnEWt7kdv76iwSZ75X0FoBP0m/v4A34Ie/8F/2oSNmK79ZuVBU7R1UJueI/lb2mM3gpJQxPgX49ZwFBXaVQpDZQRzxsR6U5rjuboAFiOoDMA+D8xTMKATBUsCKnS2NlD+Vppj6bFhW6RQt2vxqLFpjkadpA2KnyC7ZGGyQhqkqSCejbtZ3Qt/pQshbJpMs= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(10070799003)(1800799024)(7416014)(376014)(366016)(23010399003)(18002099003)(22082099003)(921020)(6133799003)(56012099006);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?ZmFXeXVKQmJXVVpqMGt4RnVmZnNseG9vL2FzNG9WRXM0NnRBR095angxeTJU?= =?utf-8?B?WHl4eFMrMDQ5U2NNclRlbWFMMjZrZG54M0NYYjdaUVNRUU1uR0xWVUVFVVhh?= =?utf-8?B?VUhXclR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N2MENhRnZYTTFo?= =?utf-8?B?N1lqMklvaTlsNFdUSHdoLzY5NitYenRwY3VRRlB6eGRzNzZ5Z20zVXNOOFor?= =?utf-8?B?UFV1dlBZdHNLRHoxamlmSFJJTmxrbGxIalUrNWdJYWs4OW8xcjNKa0xhd2ky?= =?utf-8?B?bEFtRzFmRjd3Y0lYYWNCVlo0MzNVZzh3aENCQ3k5a3RyRUxHRzAwVDlXZXhr?= =?utf-8?B?aVV1U1pNcVhCQ2hVSWVnWjJZc3pWN3VXL211SkdoNUJ6ZXVmL2Y5L2VnNENC?= =?utf-8?B?Zi9QR09pdS9NQlFkcnNQSVdZMS9DRUZHQXN3SW1sYytndnZLWG9sa2lheG94?= =?utf-8?B?emNvUVdnMDFSSzJGeU5ieENxYzQxYXRYdGFKWVd5dlBIRW5kWnRVQUJKU2pp?= =?utf-8?B?UkhqS0hycUFvbTUvNjQ3Y2ZRRUEvVmgxczN6bXRQYzZZa0pJUUVjdz09?= X-OriginatorOrg: garyguo.net X-MS-Exchange-CrossTenant-Network-Message-Id: b99ee732-e639-48e0-68f0-08dec7d67654 X-MS-Exchange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:25.6254 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: teoM6klYbyYuxL0oH1f4Y5YRed6MAXRiU0h6y8foAl3yBELbN7i5TpmdWiorua0MstlaqzMKGzuSOFfgHdSCmg== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO2P265MB3263 Conceptually, `MmioRaw` is just `__iomem *`, so it should work for any types. Update the existing use case where it represents a region of compile-time known minimum size and run-time known actual size to use the dynamic-sized type `Region` instead. Rename `maxsize` method to reflect that it is the actual size (not a bound) of the region. Implement `Clone` and `Copy` manually, which cannot be derived due to the generic parameter. The use of raw pointers also cause the `Send` and `Sync` auto trait implementation to be lost, so add them back by manual implementation. Signed-off-by: Gary Guo Reviewed-by: Alexandre Courbot Suggested-by: Danilo Krummrich --- rust/kernel/devres.rs | 7 +++--- rust/kernel/io.rs | 67 +++++++++++++++++++++++++++++++++++++----------= ---- rust/kernel/io/mem.rs | 5 ++-- rust/kernel/pci/io.rs | 4 +-- 4 files changed, 57 insertions(+), 26 deletions(-) diff --git a/rust/kernel/devres.rs b/rust/kernel/devres.rs index ed30ccc6e68e..d0c677fd7932 100644 --- a/rust/kernel/devres.rs +++ b/rust/kernel/devres.rs @@ -70,14 +70,15 @@ struct Inner { /// Io, /// Mmio, /// MmioRaw, -/// PhysAddr, // +/// PhysAddr, +/// Region, // /// }, /// prelude::*, /// }; /// use core::ops::Deref; /// /// // See also [`pci::Bar`] for a real example. -/// struct IoMem(MmioRaw); +/// struct IoMem(MmioRaw>); /// /// impl IoMem { /// /// # Safety @@ -92,7 +93,7 @@ struct Inner { /// return Err(ENOMEM); /// } /// -/// Ok(IoMem(MmioRaw::new(addr as usize, SIZE)?)) +/// Ok(IoMem(MmioRaw::new_region(addr as usize, SIZE)?)) /// } /// } /// diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index 3b478dcf10f9..c64b12ade123 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -89,37 +89,67 @@ fn size(p: *const Self) -> usize { =20 /// Raw representation of an MMIO region. /// +/// `MmioRaw` is equivalent to `T __iomem *` in C. +/// /// By itself, the existence of an instance of this structure does not pro= vide any guarantees that /// the represented MMIO region does exist or is properly mapped. /// /// Instead, the bus specific MMIO implementation must convert this raw re= presentation into an /// `Mmio` instance providing the actual memory accessors. Only by the con= version into an `Mmio` /// structure any guarantees are given. -pub struct MmioRaw { - addr: usize, - maxsize: usize, +pub struct MmioRaw { + /// Pointer is in I/O address space. + /// + /// The provenance does not matter, only the address and metadata do. + ptr: *mut T, } =20 -impl MmioRaw { - /// Returns a new `MmioRaw` instance on success, an error otherwise. - pub fn new(addr: usize, maxsize: usize) -> Result { - if maxsize < SIZE { - return Err(EINVAL); +impl Copy for MmioRaw {} +impl Clone for MmioRaw { + #[inline] + fn clone(&self) -> Self { + *self + } +} + +// SAFETY: `MmioRaw` is just an address, so is thread-safe. +unsafe impl Send for MmioRaw {} +// SAFETY: `MmioRaw` is just an address, so is thread-safe. +unsafe impl Sync for MmioRaw {} + +impl MmioRaw { + /// Create a `MmioRaw` from address. + #[inline] + pub fn new(addr: usize) -> Self { + Self { + ptr: core::ptr::without_provenance_mut(addr), } + } +} =20 - Ok(Self { addr, maxsize }) +impl MmioRaw> { + /// Create a `MmioRaw` representing a I/O region with given size. + /// + /// The size is checked against the minimum size specified via const g= enerics. + #[inline] + pub fn new_region(addr: usize, size: usize) -> Result { + Ok(Self { + ptr: Region::ptr_try_from_raw_parts_mut(core::ptr::without_pro= venance_mut(addr), size)?, + }) } +} =20 +impl MmioRaw { /// Returns the base address of the MMIO region. #[inline] pub fn addr(&self) -> usize { - self.addr + self.ptr.addr() } =20 - /// Returns the maximum size of the MMIO region. + /// Returns the size of the MMIO region. #[inline] - pub fn maxsize(&self) -> usize { - self.maxsize + pub fn size(&self) -> usize { + KnownSize::size(self.ptr) } } =20 @@ -144,12 +174,13 @@ pub fn maxsize(&self) -> usize { /// Mmio, /// MmioRaw, /// PhysAddr, +/// Region, /// }, /// }; /// use core::ops::Deref; /// /// // See also `pci::Bar` for a real example. -/// struct IoMem(MmioRaw); +/// struct IoMem(MmioRaw>); /// /// impl IoMem { /// /// # Safety @@ -164,7 +195,7 @@ pub fn maxsize(&self) -> usize { /// return Err(ENOMEM); /// } /// -/// Ok(IoMem(MmioRaw::new(addr as usize, SIZE)?)) +/// Ok(IoMem(MmioRaw::new_region(addr as usize, SIZE)?)) /// } /// } /// @@ -194,7 +225,7 @@ pub fn maxsize(&self) -> usize { /// # } /// ``` #[repr(transparent)] -pub struct Mmio(MmioRaw); +pub struct Mmio(MmioRaw>); =20 /// Checks whether an access of type `U` at the given `base` and the given= `offset` /// is valid within this region. @@ -839,7 +870,7 @@ fn addr(self) -> usize { /// Returns the maximum size of this mapping. #[inline] fn maxsize(self) -> usize { - self.0.maxsize() + self.0.size() } } =20 @@ -850,7 +881,7 @@ impl Mmio { /// /// Callers must ensure that `addr` is the start of a valid I/O mapped= memory region of size /// `maxsize`. - pub unsafe fn from_raw(raw: &MmioRaw) -> &Self { + pub unsafe fn from_raw(raw: &MmioRaw>) -> &Self { // SAFETY: `Mmio` is a transparent wrapper around `MmioRaw`. unsafe { &*core::ptr::from_ref(raw).cast() } } diff --git a/rust/kernel/io/mem.rs b/rust/kernel/io/mem.rs index fc2a3e24f8d5..9e15bc8fde78 100644 --- a/rust/kernel/io/mem.rs +++ b/rust/kernel/io/mem.rs @@ -229,7 +229,7 @@ fn deref(&self) -> &Self::Target { /// start of the I/O memory mapped region. pub struct IoMem<'a, const SIZE: usize =3D 0> { dev: &'a Device, - io: MmioRaw, + io: MmioRaw>, } =20 impl<'a, const SIZE: usize> IoMem<'a, SIZE> { @@ -264,8 +264,7 @@ fn ioremap(dev: &'a Device, resource: &Resource)= -> Result { return Err(ENOMEM); } =20 - let io =3D MmioRaw::new(addr as usize, size)?; - + let io =3D MmioRaw::new_region(addr as usize, size)?; Ok(IoMem { dev, io }) } =20 diff --git a/rust/kernel/pci/io.rs b/rust/kernel/pci/io.rs index 505305cd9b86..42f840d64a6f 100644 --- a/rust/kernel/pci/io.rs +++ b/rust/kernel/pci/io.rs @@ -139,7 +139,7 @@ fn maxsize(self) -> usize { /// memory mapped PCI BAR and its size. pub struct Bar<'a, const SIZE: usize =3D 0> { pdev: &'a Device, - io: MmioRaw, + io: MmioRaw>, num: i32, } =20 @@ -179,7 +179,7 @@ pub(super) fn new( return Err(ENOMEM); } =20 - let io =3D match MmioRaw::new(ioptr, len as usize) { + let io =3D match MmioRaw::new_region(ioptr, len as usize) { Ok(io) =3D> io, Err(err) =3D> { // SAFETY: --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from CWXP265CU010.outbound.protection.outlook.com (mail-ukwestazon11022126.outbound.protection.outlook.com [52.101.101.126]) (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 7079E436350; Thu, 11 Jun 2026 16:28:34 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.101.126 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195317; cv=fail; b=LNvUgIiaC/NEFKUtYgQhk5Hv86mD+5qY6Tau5nQrUn0YMkKazsH4CcVrqJl3z6t1uCW1dA6gLBEC/ankyM1NPvp5BFEwsySPOBEuyRe6iMZpnbELXsN/5NXQ3RUsbrfuzyCyORshO/hsnoNfNi+fb0V+YghHu6G6tRmf1gpSb9A= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195317; c=relaxed/simple; bh=NBpZ6XUymQOmrt3yk2SJTf8t9CMEp2VjM4ZTi8GWPec=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=ndmMPOAYRodqmNe2NUlgy15UMy/E3GUGh6XFHvhFvbqre7kYvczU+QjYneajvPsZXsEr/9dBaBEogpBU4q+ydeTkFS6JAW8cI7mqe5Kpaf433AcySOGHTM1I98rbXi4ASPTS5Ic+Sm1W5PY4PWSQKHhla8vM94VJcI0gnDucMNc= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=M3a4Tf5A; arc=fail smtp.client-ip=52.101.101.126 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="M3a4Tf5A" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=Ayzvg+AFlSNUAHJ7kWtiW+RBch7uOCnSlFW1Wl0AH1EFMm7K1Eu2rd0qR3BAzP3EqVABkfk5Br3ooLmOy8EI9VCShqKZVm2ag+qnplHSWTyMu6zvwiDaPmiMhppPC+3I0kRhbfFTZ1Yq/rP3DC11dTpyLlz5VwUUbEZoEaZNtDLb5uH/LHJdOVWGrAg1kT6mABEJAQWQmWP7vxI2ByfygTS1pXqFCPGRrhqnkfD80Rwk9EOqfEmsA2ICR6s2M/vPdu7eo2Ws6/rD7wX2Pz+RXSEa9Pe23Z/KKCEZJnACb2KlPbvQXINah6A4VaBhzsW6l+cIYB+t9/E9kR4fzlQzaA== 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=iZWvR16iEy73XiDLaDuQn5boJIYryCI5q2a3poJsPKw=; b=luZsjtVAQHywCwUD1QsXdqsU9HxzaIVqfuZhb0XZ7D4lPTmwVb4rCsBwAqTXScizHPI4ot5XmxPmHCh16NJ4umajuhImvtLKkaR1Pax3RBuJ/GfQZPFuEhxciCtVuy/z6d6PpDyO6CNWUm0NReug6QSnh9GtgmTkPzLel3qfj+ZltifTsMn4QKoyW7JVrbPsVKJpygDgZiQmpsFsylLLNFGeMeNZdGQQ70BGghFF8JqiYFX47KjLK0yAlQUE4stf8+uslaaJiRr3due/q/w/mu+ab2gXc3gGhb9TLfDbAVlZFsBTWH019v232c0msMcIn0rDWkgBGDLG6QNzQjpC4A== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=iZWvR16iEy73XiDLaDuQn5boJIYryCI5q2a3poJsPKw=; b=M3a4Tf5AS8q2TTq6CaKAPwn3VsxhcKTrnnCRszNuECLa9fINkO0xPLfiHhhzY5LgWT6UKwW2b2U8R3P2NLr3ldOBRaJK7xfa1JxX/Idt0wcTzBvELzln3nK3j94nKI8dIrAz7Os9xZk6PSaiLtfFrURdlHns/0a7v1xBJ1ubqiU= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO4P265MB6525.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:2e7::9) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.11; Thu, 11 Jun 2026 16:28:26 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:26 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:08 +0100 Subject: [PATCH v4 06/20] rust: io: rename `Mmio` to `MmioOwned` Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-6-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195301; l=16838; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=NBpZ6XUymQOmrt3yk2SJTf8t9CMEp2VjM4ZTi8GWPec=; b=m/DB8HpVWRgfDzJ/p65jSUyNUdYuAuA1jsnH2KdL7g1zk4xzjPmJJcDuAjkM4pqSbQDpiik2D kIV6KEySu75DBbSaErkVUOcR1Qjr8uSWiSQPddTVQO81w3oObKQ/Prd X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO4P265MB6525:EE_ X-MS-Office365-Filtering-Correlation-Id: a84a6e2b-1d63-4736-97ef-08dec7d676b2 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|23010399003|376014|7416014|366016|1800799024|10070799003|921020|6133799003|56012099006|5023799004|22082099003|18002099003; X-Microsoft-Antispam-Message-Info: xyD0GLVjSR5LIQJWRRV63U8qYfHKR4Dsjq37PSwzVHWtQVnTApTmOaR2OiYohZLiK8mTb716+9fJdS00tZNqijiwDgZhaVIJ8PJdZey57l8p0vFwQ3ISMPYgLExJiashQyhcZRkor8a3R6GEDrlB1mFZcFd+acSfib4BXI+lk+8AvmYJkbp9UEyvVPrIgXGQ3efEYjvR2hc+rxil6eDC1uI4oNK+c18QUu4MIt+yo/l6fWfI+ZOYW1IbDwwwFT0Q74jVg1UcUyqcto6601qdSstybdV1g+UlJM9/B/62FliC+Snn55w7h0X4bsE+YRWU+dSqFrFnV7EGF2LzMRV/jBomoHCZ+ltTDKHTcOVjZbOBEDImbHfo01DkvOt7fl6D26E49h9nkLRM9nZg8V4tt5DBXppUhwrk5ZvpkQ0zFilIgcc1dTu+tkce5X9em5SE6rY401NIplJ9K6jKD5JTlhm+8KwXffCKOWpD/TzQ7OghaUnV0TJdY42RE6GyoG6GXWjkH+Yr3bMjBZrSkyBokup7ZJY55EQJYk+p6d4PLcyZBmDEaTYhuoWFLbz0sRxH6ARkjFAZ88GybH7YygsSIkL8luhCB64P4WSBIEFKFYtrcv66lzsD6by7n75bY9lthGHuO2FcYOUc6HyO1bSLXhzJIs7CQ8TUt7ZJT3LYHweY2Ny8vEEm9iTFmuewFe6HdxyH2MYwTBT+Xli18JacTNrrxi8/EkJNvWvI2x5WtsQ= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(23010399003)(376014)(7416014)(366016)(1800799024)(10070799003)(921020)(6133799003)(56012099006)(5023799004)(22082099003)(18002099003);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam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3VlYvQUZ5NEtsYmNYWHVU?= =?utf-8?B?MzhjczV3Z3ZoS2ZTUmw0RHkxbW9BTGE4ZzJuZjRhUjUvWnBXeWc5aTZMaTlh?= =?utf-8?B?c1NVWlhYTXVCVTN3SjJxbk5qeHBLaUhtdktqVldJV1c1ZUhheWJxN0RESFBo?= =?utf-8?B?Zm1TMHByek04YldLQjRCWUs1ekhQRDAwcGVtemxRbjlJU0EzMEgrMEFYZVdS?= =?utf-8?B?ZjI0WmRrd3MvclMxWjVja0lFZGw2SjlQczA4QVNoYkhrcDZEMGtLckNhR0Rh?= =?utf-8?B?blFUWkUyVVZrVXlKNWdtSTlKckV3eDEzQ0liNTRwcHMyY3JEZmxpa0N3YnJV?= =?utf-8?B?K3BzeFprVmlNMlQ2SHBFbDBGYXFnMi94VjFwYzMzV0Y2Q1dVUHNNd0huajRO?= =?utf-8?B?dCtaSHNDM3JRRFBWemtEZFpmRDVNUHZtTEJFRzdzdGx3M2NibWxhZlJRazBa?= =?utf-8?B?Mk1NRTBhMGlCYk5SQXRQS21ZelhVclY4MFY4Q1Bmc255bnJuUDFzWUN5cXJT?= =?utf-8?B?c3RNdmFyZWNSeFNXK2k1M0dBM2FNd09tZ2srb3JYcDA2bVgySU5CZz09?= X-OriginatorOrg: garyguo.net X-MS-Exchange-CrossTenant-Network-Message-Id: a84a6e2b-1d63-4736-97ef-08dec7d676b2 X-MS-Exchange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:26.2463 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: eXAXLSehtmZuEauHqfdFKZbUDA1AAP/zx6Qr8DT3DHs2vknfAbw3laHpTYbsvvuDBF823YIcqS9+gEgFIN/I4Q== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO4P265MB6525 Most users would more commonly reach out to a view of `Mmio` rather than an owned instance of `Mmio`. Only implementor of `Io` like `Bar` or `IoMem` would need the owned version. Thus, rename `Mmio` to `MmioOwned` so that the name `Mmio` can be used for the view type instead. Signed-off-by: Gary Guo Reviewed-by: Alexandre Courbot Suggested-by: Danilo Krummrich --- rust/kernel/devres.rs | 6 ++-- rust/kernel/io.rs | 77 +++++++++++++++++++++++-------------------= ---- rust/kernel/io/mem.rs | 8 ++--- rust/kernel/io/poll.rs | 8 ++--- rust/kernel/io/register.rs | 24 +++++++-------- rust/kernel/pci/io.rs | 6 ++-- 6 files changed, 65 insertions(+), 64 deletions(-) diff --git a/rust/kernel/devres.rs b/rust/kernel/devres.rs index d0c677fd7932..aed0c994fd30 100644 --- a/rust/kernel/devres.rs +++ b/rust/kernel/devres.rs @@ -68,7 +68,7 @@ struct Inner { /// devres::Devres, /// io::{ /// Io, -/// Mmio, +/// MmioOwned, /// MmioRaw, /// PhysAddr, /// Region, // @@ -105,11 +105,11 @@ struct Inner { /// } /// /// impl Deref for IoMem { -/// type Target =3D Mmio; +/// type Target =3D MmioOwned; /// /// fn deref(&self) -> &Self::Target { /// // SAFETY: The memory range stored in `self` has been properly= mapped in `Self::new`. -/// unsafe { Mmio::from_raw(&self.0) } +/// unsafe { MmioOwned::from_raw(&self.0) } /// } /// } /// # fn no_run(dev: &Device) -> Result<(), Error> { diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index c64b12ade123..9ca0d325da50 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -95,8 +95,8 @@ fn size(p: *const Self) -> usize { /// the represented MMIO region does exist or is properly mapped. /// /// Instead, the bus specific MMIO implementation must convert this raw re= presentation into an -/// `Mmio` instance providing the actual memory accessors. Only by the con= version into an `Mmio` -/// structure any guarantees are given. +/// `MmioOwned` instance providing the actual memory accessors. Only by th= e conversion into an +/// `MmioOwned` structure any guarantees are given. pub struct MmioRaw { /// Pointer is in I/O address space. /// @@ -171,7 +171,7 @@ pub fn size(&self) -> usize { /// ffi::c_void, /// io::{ /// Io, -/// Mmio, +/// MmioOwned, /// MmioRaw, /// PhysAddr, /// Region, @@ -207,11 +207,11 @@ pub fn size(&self) -> usize { /// } /// /// impl Deref for IoMem { -/// type Target =3D Mmio; +/// type Target =3D MmioOwned; /// /// fn deref(&self) -> &Self::Target { /// // SAFETY: The memory range stored in `self` has been properly= mapped in `Self::new`. -/// unsafe { Mmio::from_raw(&self.0) } +/// unsafe { MmioOwned::from_raw(&self.0) } /// } /// } /// @@ -225,7 +225,7 @@ pub fn size(&self) -> usize { /// # } /// ``` #[repr(transparent)] -pub struct Mmio(MmioRaw>); +pub struct MmioOwned(MmioRaw>); =20 /// Checks whether an access of type `U` at the given `base` and the given= `offset` /// is valid within this region. @@ -536,10 +536,10 @@ fn write64(self, value: u64, offset: usize) /// ```no_run /// use kernel::io::{ /// Io, - /// Mmio, + /// MmioOwned, /// }; /// - /// fn do_reads(io: &Mmio) -> Result { + /// fn do_reads(io: &MmioOwned) -> Result { /// // 32-bit read from address `0x10`. /// let v: u32 =3D io.try_read(0x10)?; /// @@ -570,10 +570,10 @@ fn try_read(self, location: L) -> Result /// ```no_run /// use kernel::io::{ /// Io, - /// Mmio, + /// MmioOwned, /// }; /// - /// fn do_writes(io: &Mmio) -> Result { + /// fn do_writes(io: &MmioOwned) -> Result { /// // 32-bit write of value `1` at address `0x10`. /// io.try_write(0x10, 1u32)?; /// @@ -608,7 +608,7 @@ fn try_write(self, location: L, value: T) -> Resu= lt /// use kernel::io::{ /// register, /// Io, - /// Mmio, + /// MmioOwned, /// }; /// /// register! { @@ -624,7 +624,7 @@ fn try_write(self, location: L, value: T) -> Resu= lt /// } /// } /// - /// fn do_write_reg(io: &Mmio) -> Result { + /// fn do_write_reg(io: &MmioOwned) -> Result { /// /// io.try_write_reg(VERSION::new(1, 0)) /// } @@ -653,10 +653,10 @@ fn try_write_reg(self, value: V) -> Result /// ```no_run /// use kernel::io::{ /// Io, - /// Mmio, + /// MmioOwned, /// }; /// - /// fn do_update(io: &Mmio<0x1000>) -> Result { + /// fn do_update(io: &MmioOwned<0x1000>) -> Result { /// io.try_update(0x10, |v: u32| { /// v + 1 /// }) @@ -690,10 +690,10 @@ fn try_update(self, location: L, f: F) -> Re= sult /// ```no_run /// use kernel::io::{ /// Io, - /// Mmio, + /// MmioOwned, /// }; /// - /// fn do_reads(io: &Mmio<0x1000>) { + /// fn do_reads(io: &MmioOwned<0x1000>) { /// // 32-bit read from address `0x10`. /// let v: u32 =3D io.read(0x10); /// @@ -722,10 +722,10 @@ fn read(self, location: L) -> T /// ```no_run /// use kernel::io::{ /// Io, - /// Mmio, + /// MmioOwned, /// }; /// - /// fn do_writes(io: &Mmio<0x1000>) { + /// fn do_writes(io: &MmioOwned<0x1000>) { /// // 32-bit write of value `1` at address `0x10`. /// io.write(0x10, 1u32); /// @@ -756,7 +756,7 @@ fn write(self, location: L, value: T) /// use kernel::io::{ /// register, /// Io, - /// Mmio, + /// MmioOwned, /// }; /// /// register! { @@ -772,7 +772,7 @@ fn write(self, location: L, value: T) /// } /// } /// - /// fn do_write_reg(io: &Mmio<0x1000>) { + /// fn do_write_reg(io: &MmioOwned<0x1000>) { /// io.write_reg(VERSION::new(1, 0)); /// } /// ``` @@ -800,10 +800,10 @@ fn write_reg(self, value: V) /// ```no_run /// use kernel::io::{ /// Io, - /// Mmio, + /// MmioOwned, /// }; /// - /// fn do_update(io: &Mmio<0x1000>) { + /// fn do_update(io: &MmioOwned<0x1000>) { /// io.update(0x10, |v: u32| { /// v + 1 /// }) @@ -846,19 +846,19 @@ unsafe fn io_write(self, value: $ty, address: usize) { } =20 // MMIO regions support 8, 16, and 32-bit accesses. -impl_mmio_io_capable!(Mmio, u8, readb, writeb); -impl_mmio_io_capable!(Mmio, u16, readw, writew); -impl_mmio_io_capable!(Mmio, u32, readl, writel); +impl_mmio_io_capable!(MmioOwned, u8, readb, writeb); +impl_mmio_io_capable!(MmioOwned, u16, readw, writew); +impl_mmio_io_capable!(MmioOwned, u32, readl, writel); // MMIO regions on 64-bit systems also support 64-bit accesses. impl_mmio_io_capable!( - Mmio, + MmioOwned, #[cfg(CONFIG_64BIT)] u64, readq, writeq ); =20 -impl<'a, const SIZE: usize> Io for &'a Mmio { +impl<'a, const SIZE: usize> Io for &'a MmioOwned { type Target =3D Region; =20 /// Returns the base address of this mapping. @@ -874,27 +874,28 @@ fn maxsize(self) -> usize { } } =20 -impl Mmio { - /// Converts an `MmioRaw` into an `Mmio` instance, providing the acces= sors to the MMIO mapping. +impl MmioOwned { + /// Converts an `MmioRaw` into an `MmioOwned` instance, providing the = accessors to the MMIO + /// mapping. /// /// # Safety /// /// Callers must ensure that `addr` is the start of a valid I/O mapped= memory region of size /// `maxsize`. pub unsafe fn from_raw(raw: &MmioRaw>) -> &Self { - // SAFETY: `Mmio` is a transparent wrapper around `MmioRaw`. + // SAFETY: `MmioOwned` is a transparent wrapper around `MmioRaw`. unsafe { &*core::ptr::from_ref(raw).cast() } } } =20 -/// [`Mmio`] wrapper using relaxed accessors. +/// [`MmioOwned`] wrapper using relaxed accessors. /// /// This type provides an implementation of [`Io`] that uses relaxed I/O M= MIO operands instead of /// the regular ones. /// -/// See [`Mmio::relaxed`] for a usage example. +/// See [`MmioOwned::relaxed`] for a usage example. #[repr(transparent)] -pub struct RelaxedMmio(Mmio); +pub struct RelaxedMmio(MmioOwned); =20 impl<'a, const SIZE: usize> Io for &'a RelaxedMmio { type Target =3D Region; @@ -910,7 +911,7 @@ fn maxsize(self) -> usize { } } =20 -impl Mmio { +impl MmioOwned { /// Returns a [`RelaxedMmio`] reference that performs relaxed I/O oper= ations. /// /// Relaxed accessors do not provide ordering guarantees with respect = to DMA or memory accesses @@ -921,19 +922,19 @@ impl Mmio { /// ```no_run /// use kernel::io::{ /// Io, - /// Mmio, + /// MmioOwned, /// RelaxedMmio, /// }; /// - /// fn do_io(io: &Mmio<0x100>) { + /// fn do_io(io: &MmioOwned<0x100>) { /// // The access is performed using `readl_relaxed` instead of `r= eadl`. /// let v =3D io.relaxed().read32(0x10); /// } /// /// ``` pub fn relaxed(&self) -> &RelaxedMmio { - // SAFETY: `RelaxedMmio` is `#[repr(transparent)]` over `Mmio`, so= `Mmio` and - // `RelaxedMmio` have identical layout. + // SAFETY: `RelaxedMmio` is `#[repr(transparent)]` over `MmioOwned= `, so `MmioOwned` + // and `RelaxedMmio` have identical layout. unsafe { core::mem::transmute(self) } } } diff --git a/rust/kernel/io/mem.rs b/rust/kernel/io/mem.rs index 9e15bc8fde78..8f6c257c5b8e 100644 --- a/rust/kernel/io/mem.rs +++ b/rust/kernel/io/mem.rs @@ -16,7 +16,7 @@ Region, Resource, // }, - Mmio, + MmioOwned, MmioRaw, // }, prelude::*, @@ -211,7 +211,7 @@ pub fn into_devres(self) -> Result>> { } =20 impl Deref for ExclusiveIoMem<'_, SIZE> { - type Target =3D Mmio; + type Target =3D MmioOwned; =20 fn deref(&self) -> &Self::Target { &self.iomem @@ -291,10 +291,10 @@ fn drop(&mut self) { } =20 impl Deref for IoMem<'_, SIZE> { - type Target =3D Mmio; + type Target =3D MmioOwned; =20 fn deref(&self) -> &Self::Target { // SAFETY: Safe as by the invariant of `IoMem`. - unsafe { Mmio::from_raw(&self.io) } + unsafe { MmioOwned::from_raw(&self.io) } } } diff --git a/rust/kernel/io/poll.rs b/rust/kernel/io/poll.rs index 75d1b3e8596c..79828a8006b5 100644 --- a/rust/kernel/io/poll.rs +++ b/rust/kernel/io/poll.rs @@ -47,14 +47,14 @@ /// ```no_run /// use kernel::io::{ /// Io, -/// Mmio, +/// MmioOwned, /// poll::read_poll_timeout, // /// }; /// use kernel::time::Delta; /// /// const HW_READY: u16 =3D 0x01; /// -/// fn wait_for_hardware(io: &Mmio) -> Result { +/// fn wait_for_hardware(io: &MmioOwned) -> Resul= t { /// read_poll_timeout( /// // The `op` closure reads the value of a specific status regis= ter. /// || io.try_read16(0x1000), @@ -134,14 +134,14 @@ pub fn read_poll_timeout( /// ```no_run /// use kernel::io::{ /// Io, -/// Mmio, +/// MmioOwned, /// poll::read_poll_timeout_atomic, // /// }; /// use kernel::time::Delta; /// /// const HW_READY: u16 =3D 0x01; /// -/// fn wait_for_hardware(io: &Mmio) -> Result { +/// fn wait_for_hardware(io: &MmioOwned) -> Resul= t { /// read_poll_timeout_atomic( /// // The `op` closure reads the value of a specific status regis= ter. /// || io.try_read16(0x1000), diff --git a/rust/kernel/io/register.rs b/rust/kernel/io/register.rs index 64fff9193a13..242ad96ac805 100644 --- a/rust/kernel/io/register.rs +++ b/rust/kernel/io/register.rs @@ -58,7 +58,7 @@ //! }, //! num::Bounded, //! }; -//! # use kernel::io::Mmio; +//! # use kernel::io::MmioOwned; //! # register! { //! # pub BOOT_0(u32) @ 0x00000100 { //! # 15:8 vendor_id; @@ -66,7 +66,7 @@ //! # 3:0 minor_revision; //! # } //! # } -//! # fn test(io: &Mmio<0x1000>) { +//! # fn test(io: &MmioOwned<0x1000>) { //! # fn obtain_vendor_id() -> u8 { 0xff } //! //! // Read from the register's defined offset (0x100). @@ -447,7 +447,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// Io, /// }, /// }; -/// # use kernel::io::Mmio; +/// # use kernel::io::MmioOwned; /// /// register! { /// FIXED_REG(u32) @ 0x100 { @@ -456,7 +456,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// } /// } /// -/// # fn test(io: &Mmio<0x1000>) { +/// # fn test(io: &MmioOwned<0x1000>) { /// let val =3D io.read(FIXED_REG); /// /// // Write from an already-existing value. @@ -560,7 +560,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// Io, /// }, /// }; -/// # use kernel::io::Mmio; +/// # use kernel::io::MmioOwned; /// /// // Type used to identify the base. /// pub struct CpuCtlBase; @@ -585,7 +585,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// } /// } /// -/// # fn test(io: Mmio<0x1000>) { +/// # fn test(io: MmioOwned<0x1000>) { /// // Read the status of `Cpu0`. /// let cpu0_started =3D io.read(CPU_CTL::of::()); /// @@ -602,7 +602,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// } /// } /// -/// # fn test2(io: Mmio<0x1000>) { +/// # fn test2(io: MmioOwned<0x1000>) { /// // Start the aliased `CPU0`, leaving its other fields untouched. /// io.update(CPU_CTL_ALIAS::of::(), |r| r.with_alias_start(true)); /// # } @@ -639,7 +639,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// Io, /// }, /// }; -/// # use kernel::io::Mmio; +/// # use kernel::io::MmioOwned; /// # fn get_scratch_idx() -> usize { /// # 0x15 /// # } @@ -652,7 +652,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// } /// } /// -/// # fn test(io: &Mmio<0x1000>) +/// # fn test(io: &MmioOwned<0x1000>) /// # -> Result<(), Error>{ /// // Read scratch register 0, i.e. I/O address `0x80`. /// let scratch_0 =3D io.read(SCRATCH::at(0)).value(); @@ -725,7 +725,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// Io, /// }, /// }; -/// # use kernel::io::Mmio; +/// # use kernel::io::MmioOwned; /// # fn get_scratch_idx() -> usize { /// # 0x15 /// # } @@ -753,7 +753,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// } /// } /// -/// # fn test(io: &Mmio<0x1000>) -> Result<(), Error> { +/// # fn test(io: &MmioOwned<0x1000>) -> Result<(), Error> { /// // Read scratch register 0 of CPU0. /// let scratch =3D io.read(CPU_SCRATCH::of::().at(0)); /// @@ -795,7 +795,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// } /// } /// -/// # fn test2(io: &Mmio<0x1000>) -> Result<(), Error> { +/// # fn test2(io: &MmioOwned<0x1000>) -> Result<(), Error> { /// let cpu0_status =3D io.read(CPU_FIRMWARE_STATUS::of::()).status(= ); /// # Ok(()) /// # } diff --git a/rust/kernel/pci/io.rs b/rust/kernel/pci/io.rs index 42f840d64a6f..e0acb62f58a2 100644 --- a/rust/kernel/pci/io.rs +++ b/rust/kernel/pci/io.rs @@ -10,7 +10,7 @@ io::{ Io, IoCapable, - Mmio, + MmioOwned, MmioRaw, Region, // }, @@ -242,11 +242,11 @@ fn drop(&mut self) { } =20 impl Deref for Bar<'_, SIZE> { - type Target =3D Mmio; + type Target =3D MmioOwned; =20 fn deref(&self) -> &Self::Target { // SAFETY: By the type invariant of `Self`, the MMIO range in `sel= f.io` is properly mapped. - unsafe { Mmio::from_raw(&self.io) } + unsafe { MmioOwned::from_raw(&self.io) } } } =20 --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from CWXP265CU010.outbound.protection.outlook.com (mail-ukwestazon11022106.outbound.protection.outlook.com [52.101.101.106]) (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 8063541931D; Thu, 11 Jun 2026 16:28:30 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.101.106 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195312; cv=fail; b=dVKgws8MWvh/eAjU80JhVNhcayg9JhhxlmCBl6/s+aUrLJF/Q7NENSf3d9uqIjK9Lb0CcDh0aU6H25StKAWEl4bzGoVwWJSbEGRPa5rJGtsol1cS/WGSFOgIQkwFa0dMzMxrh4FS0uizbBybXvKuGgjDqwJP/MbE8X5jc1kv7+c= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195312; c=relaxed/simple; bh=kZBNsPkay2J/c/qRJQEZ3Wab5O9w345WmRB9JEIlcC4=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=Q96dSu5ekQ8AWZfg3KQViZO2/0KlO3yV/46UJu/f+o69tfTJ30ALM0x8eCxaPLnKFP5hl4Dhl+nPDarryY+ovWwd9DBCFEFpfHfLknYtweVbhpNysB+wnfqEOCkkwf3WSBfHPqXg3PJBWXTbDvx2QoxsmTqNRZAABhve3JgjRm0= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=nH8Ujydk; arc=fail smtp.client-ip=52.101.101.106 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="nH8Ujydk" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=wDk2hJRZJcQ/uCvLlAJbmjhV2raxFX/adbG7uD9rg0CEUXvnF4pNZcC8nNFyOrmh/5bEOiTEWDuZ58tLP2Cf0HO26IpGxlsCXMzZhUHuXE6coLj/0jtpH1ZT3zcF1oQPW0SQE0cdIyqwb0Ajmw2RHDR2Zd/zwEPmdZ/MXDAmVDYxPr4e6XrjMeyAsA8cgv3HV/1fSZ37LYnw4GnPmack2Cu2hm5Wt0R1jN65HAo978bF4JGYIHVJQ8ambdATIzONg7a4zqx9g1NmKe2UIzDXblA+7GIDWUJC0dXy5Kg0DCLMP7m3SwuRMK7Rue7C79rys414yw6ZW4fckIezgVVEGA== 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=/JR7U0Sf1KcLY0zoisZpR1s4x1O+lNuvo1axQDaSOtk=; b=gksfLRzq/vI8Se07XLyZe5gpq3W6YtJEnlmnuejAbQ+G+begvxnPf0HEDW1QVS2mlNdZFhaLVaiT9ShxuirbnXf0Ja3qCQNledCSfxSgn/2OCAXu5yXBjlYMitwibwONlyOfhDdxOi3ASQj84I/F/aBDIwIr6bM0hngfa+a3K3K6T4TaNX3OuAsl3RcwG+njR55oOFTx5APO0BZc0rUtGOGfb9aC3VnC1TKSUM3916RElhZp2b446EjRM7lbIb48uStcg0aWyukBhTryFpgC5FCQctKVg4qZeXtJ4WAhM1gnbPqoo/cdVXfwSTV90HPPy/MF/dhFnUH+h9eAHMQFNw== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=/JR7U0Sf1KcLY0zoisZpR1s4x1O+lNuvo1axQDaSOtk=; b=nH8Ujydkzpw43yt8iOYcNcWqCakccwVunpE6ovJpvmLhhyLaEZJPMqYOB9oZws9pfncdgChbdptjjfZM0YuPm4CveE0D2mb2uBhn4ZCVZMFAnEu0vmYI3jqxUbnia95cwrewo8PHWFzfYqmgQ7mmZ9NXQhYJfBuXvexSP5UtluU= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO4P265MB6525.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:2e7::9) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.11; Thu, 11 Jun 2026 16:28:27 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:27 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:09 +0100 Subject: [PATCH v4 07/20] rust: io: implement `Mmio` as view type Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-7-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195301; l=16840; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=kZBNsPkay2J/c/qRJQEZ3Wab5O9w345WmRB9JEIlcC4=; b=iJkkyL8jnoIEN/vznEU5qEQFykBpDw7ql3NMcWR9rmKTdSnTZRSdpe3jxSPV6BAmGCybTkzlI d3in4J+9jSUCQRfDcjHX+ZEefwTj3QV1nE7YcjchauS5d2BVK/fUrRo X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO4P265MB6525:EE_ X-MS-Office365-Filtering-Correlation-Id: c310b527-bfb9-4498-57fe-08dec7d6770b X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|23010399003|376014|7416014|366016|1800799024|10070799003|921020|6133799003|56012099006|5023799004|22082099003|18002099003; X-Microsoft-Antispam-Message-Info: /ZM7en63rCYdLn4Ane+WOQtyPJ5+vez5WzXX9BcoUq5wBa3yQJ1qQ8hCMNtGKZTw4Z+mt5+Kx1F06kr+E7WhUduaDv463T+1FdL+sl4flZyUL3Qlh06ye1p92ZkO+iKSxu7qohDNSOgVuTlpMGymAXK9gFnoMetvXWurpCOV37DxhW9AGifBrEDgjSM0JokTQ0tzF8STQ27aOYQ7jHnbWEPfNf15N7cRbtkRLBnvg9Eh6yfLEkeiU4SKd0V4w/VMszPBWVWEOq5S6zO+zmUN8RO1iqYeAfANCEWxLlRXH3NgStcMy4wZ+ogm74UCV+iOTZYjwnbnmQda5PewYLWCTmPrb0EM5P8c08bHhkZHl2OvpsdcV6KAjNrqvxwnz2xz8sXu+V6aPDPs6HG9wBIYC97ucEhJ8ZHN7+3XQtIxqC7woyJqKyjePaGazvcnTW1Nk92ubLfVv2gXwinNwmvp7lUY0b+6o7HICMz0UEaNMgLXIWPpDJCwIeUZZI4w4bABBeipWkD6oVdN1m5j+ocqDvUqbKzBYjVJA4LuzRZKYJX/JFzBK/lgTaKRWYnZ7YCAO2D/U99B4t33hwRSnajfp2y4+9w6D1wKiaIZoWAJbK/zjEymK8sHx4qIRvqa0+K06H//0M6fwidT1ZFMH/2B/Jnw+ctSZQPj4WrdaDxRIQ5d6st098kFyE2TCr+xG4KJSJeAQm7Cymhb+gqLv+N9xVupO8PZ6yCof7txFffa4Dc= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(23010399003)(376014)(7416014)(366016)(1800799024)(10070799003)(921020)(6133799003)(56012099006)(5023799004)(22082099003)(18002099003);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?RkZLNmxSS29DOGZJZytxZjdnQjVvQjhvSzNDdjF4SHcxdnFSSFZ0bHI4RG5Z?= =?utf-8?B?NXo4clRRaWE3cG8xaStJOUdjQUF4Ny9MeVY0azlqT2ErN0MrQWpJSHcwaVoy?= =?utf-8?B?eThJWWswbEt5NnRVa3B2cW52V0dSR3JzR04rWGxKSVJMQ0swL2EySXRuZDFN?= =?utf-8?B?M0pzTXFvQXloa0xJK1lPbDVYclN0eWFvdDRmOHpWWWJpRzhheTFRTlNlTW43?= =?utf-8?B?YmlidGlsYkdndnI4TjZRWXI4V1BLUFdYdkhwb25jZjVmNkd6ZUE1MXpwQ2dM?= =?utf-8?B?Mm9jUDR0ejdKVjFtdXU1S3p1WGZ1eC8xSmhveDVNWjZ1clJJbkc1K2tXWGdm?= =?utf-8?B?QUNZUWJiRytZeFQyR09VWUsyZ0Y0UWoveEpzTG02NkdRUDNPVStNakMvRnRv?= =?utf-8?B?TVkvWEZic3F1N053bU5FaWhNQ3JOUTRUUDRCcHJ3WkRscXpjVDZLMkdIR1Mv?= =?utf-8?B?K1F5SExEZWJTSjUzRVhoZlQzVWIyQ0g0WE9EaytDdDNJVmF0OGNOKzFUZWhX?= =?utf-8?B?Yzh2dTRkbDl2d0ZrZEhFNFZEOXhHSUV0S3RUMVE1YTZ2c09xNHU2MHE1RFVi?= =?utf-8?B?bkNXbDNGRVJrSVF6RVlQRE9lRkZrNzZv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rossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:26.8141 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: /TmSJzG+G3pCsaNEQTP42F8hbKT5r/UppZQBI8DSY83v3oyFDgjdot61Bdup0J17zRt9KntK+XPuav04lYFkcA== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO4P265MB6525 Implement `Mmio` as view type and convert `RelaxedMmio` to view type as well. I/O implementations of `MmioOwned` are changed to delegate to the `Mmio` view type. All existing users of `MmioOwned` in the documentation which do not actually reflect the owning semantics is converted. Signed-off-by: Gary Guo Reviewed-by: Alexandre Courbot Suggested-by: Danilo Krummrich --- rust/kernel/io.rs | 195 +++++++++++++++++++++++++++++++++++------= ---- rust/kernel/io/poll.rs | 10 ++- rust/kernel/io/register.rs | 24 +++--- 3 files changed, 171 insertions(+), 58 deletions(-) diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index 9ca0d325da50..3ac8b396f5a7 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -4,6 +4,10 @@ //! //! C header: [`include/asm-generic/io.h`](srctree/include/asm-generic/io.= h) =20 +use core::{ + marker::PhantomData, // +}; + use crate::{ bindings, prelude::*, @@ -536,10 +540,11 @@ fn write64(self, value: u64, offset: usize) /// ```no_run /// use kernel::io::{ /// Io, - /// MmioOwned, + /// Mmio, + /// Region, /// }; /// - /// fn do_reads(io: &MmioOwned) -> Result { + /// fn do_reads(io: Mmio<'_, Region>) -> Result { /// // 32-bit read from address `0x10`. /// let v: u32 =3D io.try_read(0x10)?; /// @@ -570,10 +575,11 @@ fn try_read(self, location: L) -> Result /// ```no_run /// use kernel::io::{ /// Io, - /// MmioOwned, + /// Mmio, + /// Region, /// }; /// - /// fn do_writes(io: &MmioOwned) -> Result { + /// fn do_writes(io: Mmio<'_, Region>) -> Result { /// // 32-bit write of value `1` at address `0x10`. /// io.try_write(0x10, 1u32)?; /// @@ -608,7 +614,8 @@ fn try_write(self, location: L, value: T) -> Resu= lt /// use kernel::io::{ /// register, /// Io, - /// MmioOwned, + /// Mmio, + /// Region, /// }; /// /// register! { @@ -624,7 +631,7 @@ fn try_write(self, location: L, value: T) -> Resu= lt /// } /// } /// - /// fn do_write_reg(io: &MmioOwned) -> Result { + /// fn do_write_reg(io: Mmio<'_, Region>) -> Result { /// /// io.try_write_reg(VERSION::new(1, 0)) /// } @@ -653,10 +660,11 @@ fn try_write_reg(self, value: V) -> Result /// ```no_run /// use kernel::io::{ /// Io, - /// MmioOwned, + /// Mmio, + /// Region, /// }; /// - /// fn do_update(io: &MmioOwned<0x1000>) -> Result { + /// fn do_update(io: Mmio<'_, Region<0x1000>>) -> Result { /// io.try_update(0x10, |v: u32| { /// v + 1 /// }) @@ -690,10 +698,11 @@ fn try_update(self, location: L, f: F) -> Re= sult /// ```no_run /// use kernel::io::{ /// Io, - /// MmioOwned, + /// Mmio, + /// Region, /// }; /// - /// fn do_reads(io: &MmioOwned<0x1000>) { + /// fn do_reads(io: Mmio<'_, Region<0x1000>>) { /// // 32-bit read from address `0x10`. /// let v: u32 =3D io.read(0x10); /// @@ -722,10 +731,11 @@ fn read(self, location: L) -> T /// ```no_run /// use kernel::io::{ /// Io, - /// MmioOwned, + /// Mmio, + /// Region, /// }; /// - /// fn do_writes(io: &MmioOwned<0x1000>) { + /// fn do_writes(io: Mmio<'_, Region<0x1000>>) { /// // 32-bit write of value `1` at address `0x10`. /// io.write(0x10, 1u32); /// @@ -756,7 +766,8 @@ fn write(self, location: L, value: T) /// use kernel::io::{ /// register, /// Io, - /// MmioOwned, + /// Mmio, + /// Region, /// }; /// /// register! { @@ -772,7 +783,7 @@ fn write(self, location: L, value: T) /// } /// } /// - /// fn do_write_reg(io: &MmioOwned<0x1000>) { + /// fn do_write_reg(io: Mmio<'_, Region<0x1000>>) { /// io.write_reg(VERSION::new(1, 0)); /// } /// ``` @@ -800,10 +811,11 @@ fn write_reg(self, value: V) /// ```no_run /// use kernel::io::{ /// Io, - /// MmioOwned, + /// Mmio, + /// Region, /// }; /// - /// fn do_update(io: &MmioOwned<0x1000>) { + /// fn do_update(io: Mmio<'_, Region<0x1000>>) { /// io.update(0x10, |v: u32| { /// v + 1 /// }) @@ -827,16 +839,72 @@ fn update(self, location: L, f: F) } } =20 +/// A view of memory-mapped I/O region. +/// +/// # Invariant +/// +/// `ptr` points to a valid and aligned memory-mapped I/O region for the d= uration lifetime `'a`. +pub struct Mmio<'a, T: ?Sized> { + ptr: *mut T, + phantom: PhantomData<&'a ()>, +} + +impl Copy for Mmio<'_, T> {} +impl Clone for Mmio<'_, T> { + #[inline] + fn clone(&self) -> Self { + *self + } +} + +impl<'a, T: ?Sized> Mmio<'a, T> { + /// Create a `Mmio`, providing the accessors to the MMIO mapping. + /// + /// # Safety + /// + /// `raw` represents an valid and aligned memory-mapped I/O region whi= le `'a` is alive. + #[inline] + pub unsafe fn from_raw(raw: MmioRaw) -> Self { + // INVARIANT: Per safety requirement. + Self { + ptr: raw.ptr, + phantom: PhantomData, + } + } +} + +// SAFETY: `Mmio<'_, T>` is conceptually `&T` but in I/O memory. +unsafe impl Send for Mmio<'_, T> {} + +// SAFETY: `Mmio<'_, T>` is conceptually `&T` but in I/O memory. +unsafe impl Sync for Mmio<'_, T> {} + +impl Io for Mmio<'_, T> { + type Target =3D T; + + #[inline] + fn addr(self) -> usize { + self.ptr.addr() + } + + #[inline] + fn maxsize(self) -> usize { + KnownSize::size(self.ptr) + } +} + /// Implements [`IoCapable`] on `$mmio` for `$ty` using `$read_fn` and `$w= rite_fn`. macro_rules! impl_mmio_io_capable { ($mmio:ident, $(#[$attr:meta])* $ty:ty, $read_fn:ident, $write_fn:iden= t) =3D> { $(#[$attr])* - impl IoCapable<$ty> for &$mmio { + impl IoCapable<$ty> for $mmio<'_, T> { + #[inline] unsafe fn io_read(self, address: usize) -> $ty { // SAFETY: By the trait invariant `address` is a valid add= ress for MMIO operations. unsafe { bindings::$read_fn(address as *const c_void) } } =20 + #[inline] unsafe fn io_write(self, value: $ty, address: usize) { // SAFETY: By the trait invariant `address` is a valid add= ress for MMIO operations. unsafe { bindings::$write_fn(value, address as *mut c_void= ) } @@ -846,17 +914,12 @@ unsafe fn io_write(self, value: $ty, address: usize) { } =20 // MMIO regions support 8, 16, and 32-bit accesses. -impl_mmio_io_capable!(MmioOwned, u8, readb, writeb); -impl_mmio_io_capable!(MmioOwned, u16, readw, writew); -impl_mmio_io_capable!(MmioOwned, u32, readl, writel); +impl_mmio_io_capable!(Mmio, u8, readb, writeb); +impl_mmio_io_capable!(Mmio, u16, readw, writew); +impl_mmio_io_capable!(Mmio, u32, readl, writel); // MMIO regions on 64-bit systems also support 64-bit accesses. -impl_mmio_io_capable!( - MmioOwned, - #[cfg(CONFIG_64BIT)] - u64, - readq, - writeq -); +#[cfg(CONFIG_64BIT)] +impl_mmio_io_capable!(Mmio, u64, readq, writeq); =20 impl<'a, const SIZE: usize> Io for &'a MmioOwned { type Target =3D Region; @@ -874,6 +937,23 @@ fn maxsize(self) -> usize { } } =20 +impl<'a, const SIZE: usize, T> IoCapable for &'a MmioOwned +where + Mmio<'a, Region>: IoCapable, +{ + #[inline] + unsafe fn io_read(self, address: usize) -> T { + // SAFETY: Per safety requirement. + unsafe { self.as_view().io_read(address) } + } + + #[inline] + unsafe fn io_write(self, value: T, address: usize) { + // SAFETY: Per safety requirement. + unsafe { self.as_view().io_write(value, address) } + } +} + impl MmioOwned { /// Converts an `MmioRaw` into an `MmioOwned` instance, providing the = accessors to the MMIO /// mapping. @@ -886,32 +966,59 @@ pub unsafe fn from_raw(raw: &MmioRaw>) -= > &Self { // SAFETY: `MmioOwned` is a transparent wrapper around `MmioRaw`. unsafe { &*core::ptr::from_ref(raw).cast() } } + + /// Return a view that covers the full region. + #[inline] + pub fn as_view(&self) -> Mmio<'_, Region> { + // SAFETY: `Mmio` has same invariant as `MmioOwned`. + unsafe { Mmio::from_raw(self.0) } + } } =20 -/// [`MmioOwned`] wrapper using relaxed accessors. +/// [`Mmio`] but using relaxed accessors. /// /// This type provides an implementation of [`Io`] that uses relaxed I/O M= MIO operands instead of /// the regular ones. /// -/// See [`MmioOwned::relaxed`] for a usage example. -#[repr(transparent)] -pub struct RelaxedMmio(MmioOwned); +/// See [`Mmio::relaxed`] for a usage example. +/// +/// # Invariant +/// +/// `ptr` points to a valid and aligned memory-mapped I/O region for the d= uration lifetime `'a`. +pub struct RelaxedMmio<'a, T: ?Sized> { + ptr: *mut T, + phantom: PhantomData<&'a ()>, +} =20 -impl<'a, const SIZE: usize> Io for &'a RelaxedMmio { - type Target =3D Region; +impl Copy for RelaxedMmio<'_, T> {} +impl Clone for RelaxedMmio<'_, T> { + #[inline] + fn clone(&self) -> Self { + *self + } +} + +// SAFETY: `RelaxedMmio<'_, T>` is conceptually `&T` but in I/O memory. +unsafe impl Send for RelaxedMmio<'_, T> {} + +// SAFETY: `RelaxedMmio<'_, T>` is conceptually `&T` but in I/O memory. +unsafe impl Sync for RelaxedMmio<'_, T> {} + +impl Io for RelaxedMmio<'_, T> { + type Target =3D T; =20 #[inline] fn addr(self) -> usize { - self.0.addr() + self.ptr.addr() } =20 #[inline] fn maxsize(self) -> usize { - self.0.maxsize() + KnownSize::size(self.ptr) } } =20 -impl MmioOwned { +impl<'a, T: ?Sized> Mmio<'a, T> { /// Returns a [`RelaxedMmio`] reference that performs relaxed I/O oper= ations. /// /// Relaxed accessors do not provide ordering guarantees with respect = to DMA or memory accesses @@ -922,20 +1029,24 @@ impl MmioOwned { /// ```no_run /// use kernel::io::{ /// Io, - /// MmioOwned, + /// Mmio, + /// Region, /// RelaxedMmio, /// }; /// - /// fn do_io(io: &MmioOwned<0x100>) { + /// fn do_io(io: Mmio<'_, Region<0x100>>) { /// // The access is performed using `readl_relaxed` instead of `r= eadl`. /// let v =3D io.relaxed().read32(0x10); /// } /// /// ``` - pub fn relaxed(&self) -> &RelaxedMmio { - // SAFETY: `RelaxedMmio` is `#[repr(transparent)]` over `MmioOwned= `, so `MmioOwned` - // and `RelaxedMmio` have identical layout. - unsafe { core::mem::transmute(self) } + #[inline] + pub fn relaxed(self) -> RelaxedMmio<'a, T> { + // INVARIANT: `RelaxedMmio` has the same invariant as `Mmio`. + RelaxedMmio { + ptr: self.ptr, + phantom: PhantomData, + } } } =20 diff --git a/rust/kernel/io/poll.rs b/rust/kernel/io/poll.rs index 79828a8006b5..d75f2fcf46f2 100644 --- a/rust/kernel/io/poll.rs +++ b/rust/kernel/io/poll.rs @@ -47,14 +47,15 @@ /// ```no_run /// use kernel::io::{ /// Io, -/// MmioOwned, +/// Mmio, +/// Region, /// poll::read_poll_timeout, // /// }; /// use kernel::time::Delta; /// /// const HW_READY: u16 =3D 0x01; /// -/// fn wait_for_hardware(io: &MmioOwned) -> Resul= t { +/// fn wait_for_hardware(io: Mmio<'_, Region>) ->= Result { /// read_poll_timeout( /// // The `op` closure reads the value of a specific status regis= ter. /// || io.try_read16(0x1000), @@ -134,14 +135,15 @@ pub fn read_poll_timeout( /// ```no_run /// use kernel::io::{ /// Io, -/// MmioOwned, +/// Mmio, +/// Region, /// poll::read_poll_timeout_atomic, // /// }; /// use kernel::time::Delta; /// /// const HW_READY: u16 =3D 0x01; /// -/// fn wait_for_hardware(io: &MmioOwned) -> Resul= t { +/// fn wait_for_hardware(io: Mmio<'_, Region>) ->= Result { /// read_poll_timeout_atomic( /// // The `op` closure reads the value of a specific status regis= ter. /// || io.try_read16(0x1000), diff --git a/rust/kernel/io/register.rs b/rust/kernel/io/register.rs index 242ad96ac805..d0feaf7c8736 100644 --- a/rust/kernel/io/register.rs +++ b/rust/kernel/io/register.rs @@ -58,7 +58,7 @@ //! }, //! num::Bounded, //! }; -//! # use kernel::io::MmioOwned; +//! # use kernel::io::{Mmio, Region}; //! # register! { //! # pub BOOT_0(u32) @ 0x00000100 { //! # 15:8 vendor_id; @@ -66,7 +66,7 @@ //! # 3:0 minor_revision; //! # } //! # } -//! # fn test(io: &MmioOwned<0x1000>) { +//! # fn test(io: Mmio<'_, Region<0x1000>>) { //! # fn obtain_vendor_id() -> u8 { 0xff } //! //! // Read from the register's defined offset (0x100). @@ -447,7 +447,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// Io, /// }, /// }; -/// # use kernel::io::MmioOwned; +/// # use kernel::io::{Mmio, Region}; /// /// register! { /// FIXED_REG(u32) @ 0x100 { @@ -456,7 +456,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// } /// } /// -/// # fn test(io: &MmioOwned<0x1000>) { +/// # fn test(io: Mmio<'_, Region<0x1000>>) { /// let val =3D io.read(FIXED_REG); /// /// // Write from an already-existing value. @@ -560,7 +560,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// Io, /// }, /// }; -/// # use kernel::io::MmioOwned; +/// # use kernel::io::{Mmio, Region}; /// /// // Type used to identify the base. /// pub struct CpuCtlBase; @@ -585,7 +585,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// } /// } /// -/// # fn test(io: MmioOwned<0x1000>) { +/// # fn test(io: Mmio<'_, Region<0x1000>>) { /// // Read the status of `Cpu0`. /// let cpu0_started =3D io.read(CPU_CTL::of::()); /// @@ -602,7 +602,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// } /// } /// -/// # fn test2(io: MmioOwned<0x1000>) { +/// # fn test2(io: Mmio<'_, Region<0x1000>>) { /// // Start the aliased `CPU0`, leaving its other fields untouched. /// io.update(CPU_CTL_ALIAS::of::(), |r| r.with_alias_start(true)); /// # } @@ -639,7 +639,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// Io, /// }, /// }; -/// # use kernel::io::MmioOwned; +/// # use kernel::io::{Mmio, Region}; /// # fn get_scratch_idx() -> usize { /// # 0x15 /// # } @@ -652,7 +652,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// } /// } /// -/// # fn test(io: &MmioOwned<0x1000>) +/// # fn test(io: Mmio<'_, Region<0x1000>>) /// # -> Result<(), Error>{ /// // Read scratch register 0, i.e. I/O address `0x80`. /// let scratch_0 =3D io.read(SCRATCH::at(0)).value(); @@ -725,7 +725,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// Io, /// }, /// }; -/// # use kernel::io::MmioOwned; +/// # use kernel::io::{Mmio, Region}; /// # fn get_scratch_idx() -> usize { /// # 0x15 /// # } @@ -753,7 +753,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// } /// } /// -/// # fn test(io: &MmioOwned<0x1000>) -> Result<(), Error> { +/// # fn test(io: Mmio<'_, Region<0x1000>>) -> Result<(), Error> { /// // Read scratch register 0 of CPU0. /// let scratch =3D io.read(CPU_SCRATCH::of::().at(0)); /// @@ -795,7 +795,7 @@ fn into_io_op(self) -> (FixedRegisterLoc, T) { /// } /// } /// -/// # fn test2(io: &MmioOwned<0x1000>) -> Result<(), Error> { +/// # fn test2(io: Mmio<'_, Region<0x1000>>) -> Result<(), Error> { /// let cpu0_status =3D io.read(CPU_FIRMWARE_STATUS::of::()).status(= ); /// # Ok(()) /// # } --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from CWXP265CU010.outbound.protection.outlook.com (mail-ukwestazon11022106.outbound.protection.outlook.com [52.101.101.106]) (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 BB111426ED6; Thu, 11 Jun 2026 16:28:32 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.101.106 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195315; cv=fail; b=I5NxWfn0qctsRya4y/7L1s8cJWT9sig6RmC85UxE4ICnHjFR9YDyA7C9LDGI3PO9JQtnAbfSsv8NbInTS0wAA4XCVi29H5mOqvTvHw6cgpiYyfNmomX6gs182bqZeuUU/HnyPqmvGwvbPHC1Wu5Bk0GAIsYenHYO6Ybar3jy4bM= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195315; c=relaxed/simple; bh=K6nQV4iI8FfcvJD7Z2NsruF+J8mGKyD8IQYu0km/f30=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=ry9oAh45k0Iu324G6/WE9C2MmHbeqlOu/HEBBYq2ULhViismzDEXypTPYWv/KV/4LIA2IjR9Ks2a52eDAmbfRn0srzRFqk2GUg2AVpAUtUkjqHyYpQfK917u/WbgpRqmfufImiUPNgyYICIi3Kv4RjX+1ioUS5YHnvnb26WGADc= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=PLuelntq; arc=fail smtp.client-ip=52.101.101.106 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="PLuelntq" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=JOxxMkLSP3YlX+ssXOfmXvNsC8o1lZnIOIjXBcXoPt86oPXcEOwVtylrMNZbJRx3x5mxk3GaJxhbtR7iWIpQ9ArhMFjzfZOvMYRnRvghyvup1cbcg40SxyfU7k+165RjsaFGjKbq1jH5xh40tIt3tBXeGHLbNEgYIhBjmSzO1QoRiBO0BNv/pBmrkMiShBgQMDSj8HAF20bvxd19Fn7y1P3sUxOSBWOUoVwobI8yB1LhR+Rn93SYNUFHiIC35UhAebjbnorYzHEl77r9C+nbO72PickzVS2C0jyNPuwtAP90XGinmzU/1H7JaGAo87k6O++doVSzUWJyr26FxRAVIA== 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=iBeszMFrKEUnSD+0j3WKKXUfZgc0TI4EmSEva2w3I5U=; b=nH1ga9dcyYpv+3u4zA97LPJcwKc6N2q3CrN2Ng6rObtLmUyPUYCVRvN3dX7VkaHvVBKJSAbHXcB7IG6XZvuXsC2X5Kyx4Mk30jA5Bh1NscCVrMYQa7PfdHyKv/ySR2pw5sdZQV3/MmGF8QqqDgI+nBR0s8UDynj8ETJxepnCkp0XA+xPj+l7G1aC42favUwIWm1L/7iu7DUPCYRBxdoFp1U8+D5EwdV1Ux9t7KchJbzoyjGPgVEjg4iHFzHJk8klF9+edorjuiemhJE4N1ecDMz2M8KojIje2LBowWm7MhTYrvsOCl9ukXGhL4WVmQ7DEQVZPxio6rNwERNiEHuWTA== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=iBeszMFrKEUnSD+0j3WKKXUfZgc0TI4EmSEva2w3I5U=; b=PLuelntqXah8PFLfGUQSgMYrqG+MUULA6inx8SK8SPsMl8dom+ENx1xWcmk2HCAO49JWlPi6XkoVr7eIchNFZqcpmAnlR+Jk9755XtzKFt+4tUigxFxkjWG9cI3EhslF2fSIR6wg54cZscugmcB0+E+kaCTHhQXUgkaDlnDQVaA= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO4P265MB6525.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:2e7::9) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.11; Thu, 11 Jun 2026 16:28:27 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:27 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:10 +0100 Subject: [PATCH v4 08/20] rust: pci: io: make `ConfigSpace` a view Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-8-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195301; l=5854; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=K6nQV4iI8FfcvJD7Z2NsruF+J8mGKyD8IQYu0km/f30=; b=4m0X7pr+O7bMeachyLVlXvBsixzwEPfoXt12+sixaTZrlIpcIuhERem3wqwWocnswuKCYXQzR cKftY4AoFf4BgShAGvBMBtTWRyZaBvmRmSFibOoXycsxfg1eBdf8k3X X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO4P265MB6525:EE_ X-MS-Office365-Filtering-Correlation-Id: 3edd8112-50dd-4448-f8eb-08dec7d6775f X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|23010399003|376014|7416014|366016|1800799024|10070799003|921020|6133799003|56012099006|3023799007|5023799004|22082099003|18002099003; X-Microsoft-Antispam-Message-Info: pqhFWZZXzG2P4qHkXh0ufh18Nsx7khDsynTnpwu58NZ+bXOeccaYXMFIMZKk/OWioPbzpY2H9zoDigZA0Q/VhF6dc+h4Pj5vtTnnaoO46uI6o8dRGQLrbQzFzlWTL0pZ2jsq7tCVSYZa3q7yJQKxCW33CsXIxHUGl4QdWwpXX/YC8byq9IvfmizUkdcdRCEOrV4ejTV5efQ8avmxfTbvBMHH/zHpRnIDyZ47A6sULbnvxOOtaLoh0b53zLHMsw5egL6AKCSEizgyy6AhDwvlj41V+WhWQTAppggz+ZroZ5cBDSxXhG5Vfho/PgfSwOGqYhbm0oSO/YodC7peWOFC3jFBja9+YG4+kneyN8fPUcHAkx/q3MBePV30L7ZDQ2MNwXSDT4aMt7Z03XW9QUUxQWTphrDOoLCVHQB+FiOKHsDIcApAJj2WsMoAim7d34lphTEKjj7TEUg6VaKmFzFtKks8um6Bdp5UA7Bma58lXHzA1HZQKYT0l3Fp+sIgG5CWMz79yZd/UiLTzszYXTNvJOmtQTjFFiV+g1pzRTXU96QWJbFTYw8LqSQfLCiYP11W0c9Z+t9b0qRV/YFujyDIJifsq+Ukh5GcxpJ76zEJnp1LWdIeRykyZU3LERWMLG4rAaHJiiZSafZjvYjltsrLI+a/Odu98GCmqXht7OoZPPKOraxp4qy7a34PShFEfa9WJxhVTfaex0bKLPwmEo+q6fI4dgxkYdRGYKOBgFBSHaY= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(23010399003)(376014)(7416014)(366016)(1800799024)(10070799003)(921020)(6133799003)(56012099006)(3023799007)(5023799004)(22082099003)(18002099003);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?ZExXeDRsdXU2eG9WNm9JNm5reXN5MVBQeVlSd2tEQ0IxVW8xMzVOUUJ5WWNx?= =?utf-8?B?Q2RwWUFleGkzMU1ic3RpaVdwSUlwMk12TmVyUDgvWElSS0Rra25jcFFReTk3?= =?utf-8?B?Mm5Vcmt2T1BjbERPWFMreFlGT1V1eEk2ZURDbTRSd2hEUDUyWUk1M3lxeEpX?= =?utf-8?B?QWZML2dDcDdXUGxESWNRS1BlZk93Vjd6aVAxRHlkYm5NRldrU05XbEN5b2NT?= =?utf-8?B?SjJsYVBvQXFYL3lMV09JZGRLSHVMUU92ME90QWttSU9NT2JvUTVETFVlZmp4?= =?utf-8?B?cnNqcHNyajM1T3AySFFja2g3NS9mWHdBQ1lUTVh1M1g1YXpBSlpoV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UN0tMY2RLWDZseDRy?= =?utf-8?B?YkZGWTlCSUUzMHFGOURZL3dRTk11ei9Id09tdzlMY2RJd1gySzY3YlhINXJ0?= =?utf-8?B?VkJxN3NsVDIxcWxSMm50WmxVSFRUVTB6b2cyVUJzSXhoMFAySWd3MmhJRjFB?= =?utf-8?B?MjRhc0JiUTMxQ2E2OTVyRlpNNkVDVWtMUWRSNnZzeVo3U1JKWlhndz09?= X-OriginatorOrg: garyguo.net X-MS-Exchange-CrossTenant-Network-Message-Id: 3edd8112-50dd-4448-f8eb-08dec7d6775f X-MS-Exchange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:27.3856 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: ScyWeBjDq36HRoQGZxtbuuxitcVrTNwxHEKKMj7MYo+XLcriF2vpRUCiZA/3IvzSGrNpFiYrl5n03jRfbGwHbg== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO4P265MB6525 In order to support I/O projection, we are splitting I/O types into two categories: owned objects and views. Owned objects have a specific type that is related to setting up and tearing down, while views can have their type changed with I/O projection. Things like `IoMem` or `Bar` are owned objects, which requires setting up mapping and cleaning up on drop. On the other side, `ConfigSpace` is really just a view, as the resource is associated with the `pci::Device`. Remove the `ConfigSpaceKind` bound on `ConfigSpace` and make it a generic view. This means that `ConfigSpace` object now represents a subregion and therefore encodes offset (as address of pointers) and size (as metadata of pointers) itself. The full region case is still supported with offset 0 and size of `cfg_size`. Signed-off-by: Gary Guo Reviewed-by: Alexandre Courbot Suggested-by: Danilo Krummrich --- rust/kernel/pci/io.rs | 64 +++++++++++++++++++++++++++++------------------= ---- 1 file changed, 36 insertions(+), 28 deletions(-) diff --git a/rust/kernel/pci/io.rs b/rust/kernel/pci/io.rs index e0acb62f58a2..89f4bb483a7f 100644 --- a/rust/kernel/pci/io.rs +++ b/rust/kernel/pci/io.rs @@ -18,7 +18,6 @@ ptr::KnownSize, // }; use core::{ - marker::PhantomData, ops::Deref, // }; =20 @@ -53,33 +52,42 @@ pub const fn into_raw(self) -> usize { /// Alias for extended (4096-byte) PCIe configuration space. pub type Extended =3D Region<4096>; =20 -/// Trait for PCI configuration space size markers. -/// -/// This trait is implemented by [`Normal`] and [`Extended`] to provide -/// compile-time knowledge of the configuration space size. -pub trait ConfigSpaceKind: KnownSize {} - -impl ConfigSpaceKind for Normal {} - -impl ConfigSpaceKind for Extended {} - -/// The PCI configuration space of a device. +/// A view of PCI configuration space of a device. /// /// Provides typed read and write accessors for configuration registers /// using the standard `pci_read_config_*` and `pci_write_config_*` helper= s. /// -/// The generic parameter `S` indicates the maximum size of the configurat= ion space. -/// Use [`Normal`] for 256-byte legacy configuration space or [`Extended`]= for -/// 4096-byte PCIe extended configuration space (default). -pub struct ConfigSpace<'a, S: ?Sized + ConfigSpaceKind =3D Extended> { +/// The generic parameter `T` is the type of the view. The full configurat= ion space is also a +/// special type of view; in such cases, `T` can be [`Normal`] for 256-byt= e legacy configuration +/// space or [`Extended`] for 4096-byte PCIe extended configuration space = (default). +/// +/// # Invariants +/// +/// `ptr` is aligned and range `ptr..ptr + KnownSize::size(ptr)` is within +/// `0..pdev.cfg_size().into_raw()`. +pub struct ConfigSpace<'a, T: ?Sized =3D Extended> { pub(crate) pdev: &'a Device, - _marker: PhantomData, + ptr: *mut T, } =20 +impl Copy for ConfigSpace<'_, T> {} +impl Clone for ConfigSpace<'_, T> { + #[inline] + fn clone(&self) -> Self { + *self + } +} + +// SAFETY: `ConfigSpace<'_, T>` is conceptually `&T` but in I/O memory. +unsafe impl Send for ConfigSpace<'_, T> {} + +// SAFETY: `ConfigSpace<'_, T>` is conceptually `&T` but in I/O memory. +unsafe impl Sync for ConfigSpace<'_, T> {} + /// Implements [`IoCapable`] on [`ConfigSpace`] for `$ty` using `$read_fn`= and `$write_fn`. macro_rules! impl_config_space_io_capable { ($ty:ty, $read_fn:ident, $write_fn:ident) =3D> { - impl<'a, S: ?Sized + ConfigSpaceKind> IoCapable<$ty> for &ConfigSp= ace<'a, S> { + impl<'a, T: ?Sized> IoCapable<$ty> for ConfigSpace<'a, T> { unsafe fn io_read(self, address: usize) -> $ty { let mut val: $ty =3D 0; =20 @@ -112,19 +120,17 @@ unsafe fn io_write(self, value: $ty, address: usize) { impl_config_space_io_capable!(u16, pci_read_config_word, pci_write_config_= word); impl_config_space_io_capable!(u32, pci_read_config_dword, pci_write_config= _dword); =20 -impl<'a, S: ?Sized + ConfigSpaceKind> Io for &ConfigSpace<'a, S> { - type Target =3D S; +impl<'a, T: ?Sized + KnownSize> Io for ConfigSpace<'a, T> { + type Target =3D T; =20 - /// Returns the base address of the I/O region. It is always 0 for con= figuration space. #[inline] fn addr(self) -> usize { - 0 + self.ptr.addr() } =20 - /// Returns the maximum size of the configuration space. #[inline] fn maxsize(self) -> usize { - self.pdev.cfg_size().into_raw() + KnownSize::size(self.ptr) } } =20 @@ -281,23 +287,25 @@ pub fn cfg_size(&self) -> ConfigSpaceSize { } } =20 - /// Return an initialized normal (256-byte) config space object. + /// Return a view of the normal (256-byte) config space. pub fn config_space<'a>(&'a self) -> ConfigSpace<'a, Normal> { + // INVARIANT: null is aligned and the range is within config space. ConfigSpace { pdev: self, - _marker: PhantomData, + ptr: Normal::ptr_from_raw_parts_mut(core::ptr::null_mut(), sel= f.cfg_size().into_raw()), } } =20 - /// Return an initialized extended (4096-byte) config space object. + /// Return a view of the extended (4096-byte) config space. pub fn config_space_extended<'a>(&'a self) -> Result> { if self.cfg_size() !=3D ConfigSpaceSize::Extended { return Err(EINVAL); } =20 + // INVARIANT: null is aligned and we just checked the `cfg_size`. Ok(ConfigSpace { pdev: self, - _marker: PhantomData, + ptr: Extended::ptr_from_raw_parts_mut(core::ptr::null_mut(), 4= 096), }) } } --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from CWXP265CU010.outbound.protection.outlook.com (mail-ukwestazon11022106.outbound.protection.outlook.com [52.101.101.106]) (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 CCFEA439010; Thu, 11 Jun 2026 16:28:35 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.101.106 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195319; cv=fail; b=TsCXmuXuE9aJ3Hdsvbg63fIcpmdGS17JNWM5GYM2x518sduV3+Rd6/5NoyRAmmpVdgl37NzoOfc31GkE9hCP25zm6y7YMBk4GYVoChLprb1p9QqvpBzYTJO/rD2+DPFkYskkH1AAcO2Cc+0JPHQRSDKo47Dszz3HrVWhsiEq/bU= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195319; c=relaxed/simple; bh=aogygvAMVs9+bXGq3flUbl77HtTfoPkh+xeIlfu5bzM=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=ORlSdf5K46Eb697XcQZXAl+x/UGJJK5iv/2bpnyqmyu413JGpbtu2dvvLOmwr5JD0XvvHpRpCuNIYx4vo4kfdHTCylw8HKoT72pn0OtGfZHMwRh13uOsOcsJdD7oWVqkdKhSTqz1v0MJWpOQmITAOIS1OviNT2zGS5tjCeezQoQ= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=uTcNmNao; arc=fail smtp.client-ip=52.101.101.106 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="uTcNmNao" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=YqSAvCtUjbhZcG2cwMFEyRNv2AiPyLYJo6H8giTtRgnTa0KAVMExEFebuD8D2SjdS/2OnDG80j3Wn7XtvXMLn5f/wW49pkiv6BnEcIuRTJVUW2juQk3aRW42yae1XxGTufAG6yO25xXKYFRvj+6/5hswhBiXKLn3GjcDEaP5+jqG/p0FQMJpsqBRXLMaj+i7SNU4RVlcnYRbVzWxY+GWUQqt/DvnjdFWv8wSJD11T9j/kGjlzzmO9kUZdaSwWMB5B8O6sHk2nciv7Pb4OlWF6syYmpeGbAgQIVsHFEJITEXmPNgubZTbJBypkwKUHeYAyZ5wNp9bda2ADL0aHH+vKQ== 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=rfjvam4JclqvTAPWjS2e757MNoHOIMWPaZlWMFuLYDY=; b=iIsBXMQYmGAfRZHpyaYBH83MjX0R+jqIkYu8Zc1O29CdCD16BaZhP2PnN0cil8rm2GG9CBqtXJ9lKt2vpH9T7RatN45jl1Kl9q5/Jgncq2CssxKZ7B9DWJ835eq0ZAQXHOoeHmSxLLihdXkxJtiffGAWnTRJeoh8MLR0a/VQrSE7C04L9isa7pfDNMJ8J3n2v1/vnYuMovF5QzAUO8EhwmWA7GTmfgR54pi4KlEdymBZ3t8bGoYosLMH/HPnD0vED58wLm5skIidJaE9+ih5vtJcwzgQl7SlIh4tbGcdXgaRIKWC6WcKm+HdvycK9/ZXoVMTgwkrV+O14T2XIX1YLQ== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=rfjvam4JclqvTAPWjS2e757MNoHOIMWPaZlWMFuLYDY=; b=uTcNmNaoJhpi9IWKiplSqbWwhNodrYxxP8sh7n97+sXqXLtCqKwYMgmCkz6NozBe7CWrUKUnKJK5uBH7JACE0mWxfhrwDKeh4wUzcd3AykXG1Tfdj0Qk0FXb1iI84R+D0VCg8ZK+9yMcJLIbtTiiQtIlOoXXIBzk9ilOymSgO68= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO4P265MB6525.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:2e7::9) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.11; Thu, 11 Jun 2026 16:28:28 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:28 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:11 +0100 Subject: [PATCH v4 09/20] rust: io: use view types instead of addresses for `Io` Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-9-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195301; l=30721; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=aogygvAMVs9+bXGq3flUbl77HtTfoPkh+xeIlfu5bzM=; b=SRR6yi1FmEpAFC4SJvbBTxXyKM9BUntHOfB8DFDTxl0ZBzofa4XJ23Tylj/+9F4zdQOArYQAE 9zF4TC6buIkCeDLRM7te0GKH832wFFmFwqexCeYGnfx8k0t7saVqmDz X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO4P265MB6525:EE_ X-MS-Office365-Filtering-Correlation-Id: 9b74b187-e338-45fa-aa79-08dec7d677b9 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|23010399003|376014|7416014|366016|1800799024|10070799003|921020|6133799003|56012099006|5023799004|22082099003|18002099003; X-Microsoft-Antispam-Message-Info: m+0Dw/Cszk+PUTpN8vyemCVE5F1STBBP85ZKJQDKAP+pYoPfl01hVVX31f8FG9ynDkLqpN6+03Za11ltznRA+BpdjmvUyJor61DKmM81VZQQmjHtTfs0TVdYXuh69knBpcD4aShLDczd7eHbmxrMJLwEKy0M3xPk7Sl+vaxhw0J249xRpkyGrCLU1WH9jMYPZfvK2vvVsUosYIHLpZDSiNwhDegP74zdp/W7fXABRTpfG1yIXGDE8d6kvfbLoEKasypl6kNqFUHTSpCaCVCU68cmkeIGjMvvC4Uqyu7zEpEWfdv3/UMLUHd2CaDtyan7I2hHeujmu7w+F+xmSdoogs58Iv6gd4TXdJ+2gg/Oa3ynb53PF2gxZAqBtMfjicyhHJtv6yswW4uH/H00VUWzxQm3+GYNCU3Tlea5DAusbhGVSD4QEg4KERPkmnVefJwAl78AEBTemNr7/eNq6TM5ry+Y5WoE9g/LjeRqwWDWiyJc0h79LYTOFd7CuJ+Ix2xf+MLF+tHso3+BTF5tJN7ICiDAyzo/w+MCXsUI8sOp7qSkz445cGbrZaeqVXCZ1L2JB6KiYnQryN06t1N8qKPWDT0d7HH88Ckgb8grd8vvZ6u3P/sWCtlE0/7E7EDtY9ur4WEEd17C/d+lhbbCI4QrsilsYOx+jzJg+4sYCOGC6TcJ8nQ+zRLKbGUOP+D0DgQCcexYLv0PCVt/MdNKhqPSP81apVrnMuaKBlSItJ/KqD4= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(23010399003)(376014)(7416014)(366016)(1800799024)(10070799003)(921020)(6133799003)(56012099006)(5023799004)(22082099003)(18002099003);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?blFDNDkzZ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t?= =?utf-8?B?T3o3MVFMd1hBRlJnS081blhvREVleDIwaFdzLzlhQWNoRDF6OGRsMU5KRGdL?= =?utf-8?B?WEF0d3ZTTGNnNWRjNGtXbWo0VzN1QnV0RGpuR0tBK3d3TXg5TTB6Z1p3cGRl?= =?utf-8?B?YzJCRCtsU1RqcnFUZDNWV3c3b0wxMWdoeWxjOGNCWmo0L0JTVUhrYXlFMlN5?= =?utf-8?B?d3BMa2dBTlBPNHpWUmI5S2M0ck1LOW8veXBYbjFZOFcrR3pUbEFlTHErZGgz?= =?utf-8?B?SzRMallRTWt0UXNvdTQyOHJ0aXRzWk9LdUx3OXR6TGMrdTZjcStqK1BMOTl4?= =?utf-8?B?clFnSHBxMG9vSk9oc0VMcE5Za2UyK1JDRHVUOWJINzZ1YXpZS3dGcDVKNE9s?= =?utf-8?B?cE91M1F0QWloMzc1R1RlTUR4dHNCUVJFYlhwYWtOYlQ2TWJGcTloLyttMzYw?= =?utf-8?B?RFdUQzNPVEM3ZlI3T3RPY3ZLcjdVbVBqOVk4dDd0MlVXbGNiVlZlNE9obWtp?= =?utf-8?B?eDIrL0ZNVlo1azdSSHNRRUEzcUhPc3AyU2NoNnB2SXh4cUl4c1o2Zz09?= X-OriginatorOrg: garyguo.net X-MS-Exchange-CrossTenant-Network-Message-Id: 9b74b187-e338-45fa-aa79-08dec7d677b9 X-MS-Exchange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:27.9624 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: RXjWtgI/t/f5PFqpxvml1SBybv+3MMMQh+aqMtRYaa6NrVZ3X4FVvSPlYgz2QG6oHl2tC5xs2mPgCzgkfjOdSg== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO4P265MB6525 Currently, `io_read` and `io_write` methods require the exact type of `Io` plus an address. This means that they need to be monomorphized for each different `Io` instance. This also means that multiple I/O implementors for the same I/O kind needs to duplicate implementation (e.g. `Mmio` and `MmioOwned`). Create a new `IoBackend` trait and define these operations on it instead. The operations are just going to receive a view type and operate on them. This has the additional advantage that the invariants can be moved from the trait (and guaranteed via `unsafe`) to type invariants on the canonical view types of the backends, so `io_read` and `io_write` can be safe. Note that view type is needed; addresses are insufficient in this designk, as they do not carry sufficient information. For example, `ConfigSpace` needs `&pci::Device` in addition to the address. Signed-off-by: Gary Guo Suggested-by: Danilo Krummrich --- rust/kernel/io.rs | 345 ++++++++++++++++++++++++++--------------------= ---- rust/kernel/pci/io.rs | 70 ++++++---- 2 files changed, 224 insertions(+), 191 deletions(-) diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index 3ac8b396f5a7..e422a5ff2a5e 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -244,6 +244,38 @@ const fn offset_valid(base: usize, offset: usize, s= ize: usize) -> bool { } } =20 +/// I/O backends. +/// +/// This is an abstract representation to be implemented by arbitrary I/O +/// backends (e.g. MMIO, PCI config space, etc.). +/// +/// The base trait only defines the projection operations; which I/O metho= ds are available depends +/// on which [`IoCapable`] traits are implemented for the type. For exa= mple, for MMIO regions, +/// all widths (u8, u16, u32, and u64 on 64-bit systems) are typically sup= ported. For PCI +/// configuration space, u8, u16, and u32 are supported but u64 is not. +/// +/// This trait is separate from the `Io` trait as multiple different I/O t= ypes may share the same +/// operation. +pub trait IoBackend { + /// View type for this I/O backend. + type View<'a, T: ?Sized + KnownSize>: Io<'a, Backend =3D Self, Target = =3D T>; + + /// Convert a `view` to a raw pointer for projection. + fn as_ptr<'a, T: ?Sized + KnownSize>(view: Self::View<'a, T>) -> *mut = T; + + /// Project `view` to its subregion indicated by `ptr`. + /// + /// If input `view` is valid, returned view must also be valid. + /// + /// # Safety + /// + /// `ptr` must be a projection of `Self::as_ptr(view)`. + unsafe fn project_view<'a, T: ?Sized + KnownSize, U: ?Sized + KnownSiz= e>( + view: Self::View<'a, T>, + ptr: *mut U, + ) -> Self::View<'a, U>; +} + /// Trait indicating that an I/O backend supports operations of a certain = type and providing an /// implementation for these operations. /// @@ -252,22 +284,12 @@ const fn offset_valid(base: usize, offset: usize, = size: usize) -> bool { /// For example, a PCI configuration space may implement `IoCapable`, = `IoCapable`, /// and `IoCapable`, but not `IoCapable`, while an MMIO region o= n a 64-bit /// system might implement all four. -pub trait IoCapable { - /// Performs an I/O read of type `T` at `address` and returns the resu= lt. - /// - /// # Safety - /// - /// - The range `[address..address + size_of::()]` must be within t= he bounds of `Self`. - /// - `address` must be aligned. - unsafe fn io_read(self, address: usize) -> T; +pub trait IoCapable: IoBackend { + /// Performs an I/O read of type `T` at `view` and returns the result. + fn io_read<'a>(view: Self::View<'a, T>) -> T; =20 - /// Performs an I/O write of `value` at `address`. - /// - /// # Safety - /// - /// - The range `[address..address + size_of::()]` must be within t= he bounds of `Self`. - /// - `address` must be aligned. - unsafe fn io_write(self, value: T, address: usize); + /// Performs an I/O write of `value` at `view`. + fn io_write<'a>(view: Self::View<'a, T>, value: T); } =20 /// Describes a given I/O location: its offset, width, and type to convert= the raw value from and @@ -319,56 +341,54 @@ 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. /// -/// This is an abstract representation to be implemented by arbitrary I/O -/// backends (e.g. MMIO, PCI config space, etc.). -/// /// The [`Io`] trait provides: -/// - Base address and size information +/// - Method to convert into [`IoBackend::View`]. /// - Helper methods for offset validation and address calculation /// - Fallible (runtime checked) accessors for different data widths /// -/// Which I/O methods are available depends on which [`IoCapable`] trai= ts -/// are implemented for the type. -/// -/// # Examples -/// -/// For MMIO regions, all widths (u8, u16, u32, and u64 on 64-bit systems)= are typically -/// supported. For PCI configuration space, u8, u16, and u32 are supported= but u64 is not. -pub trait Io: Copy { +/// Which I/O methods are available depends on the associated [`IoBackend`= ] implementation. +pub trait Io<'a>: Copy { + /// Type that defines all I/O operations. + type Backend: IoBackend; + /// Type of this I/O region. For untyped regions, [`Region`] can be us= ed. type Target: ?Sized + KnownSize; =20 - /// Returns the base address of this mapping. - fn addr(self) -> usize; - - /// Returns the maximum size of this mapping. - fn maxsize(self) -> usize; + /// Return a view that covers the full region. + fn as_view(self) -> ::View<'a, Self::Targe= t>; =20 - /// Returns the absolute I/O address for a given `offset`, - /// performing compile-time bound checks. + /// Returns a view for a given `offset`, performing compile-time bound= checks. // Always inline to optimize out error path of `build_assert`. #[inline(always)] - fn io_addr_assert(self, offset: usize) -> usize { - // We cannot check alignment with `offset_valid` using `self.addr(= )`. So set 0 for it and + fn io_addr_assert(self, offset: usize) -> ::View<'a, U> { + // We cannot check alignment with `offset_valid` using `ptr.addr()= `. So set 0 for it and // ensure alignment by checking that the alignment of `U` is small= er or equal to the // alignment of `Self::Target`. const_assert!(Alignment::of::().as_usize() <=3D Self::Target::M= IN_ALIGN.as_usize()); build_assert!(offset_valid::(0, offset, Self::Target::MIN_SIZE)= ); =20 - self.addr() + offset + let view =3D self.as_view(); + let ptr =3D Self::Backend::as_ptr(view); + let projected_ptr =3D ptr.cast::().wrapping_byte_add(offset); + // SAFETY: `offset_valid` checks for size and alignment and theref= ore `projected_ptr` is a + // valid projection. + unsafe { Self::Backend::project_view(view, projected_ptr) } } =20 - /// Returns the absolute I/O address for a given `offset`, - /// performing runtime bound checks. + /// Returns a view for a given `offset`, performing runtime bound chec= ks. #[inline] - fn io_addr(self, offset: usize) -> Result { - if !offset_valid::(self.addr(), offset, self.maxsize()) { + fn io_addr(self, offset: usize) -> Result<::View<'a, U>> { + let view =3D self.as_view(); + let ptr =3D Self::Backend::as_ptr(view); + + if !offset_valid::(ptr.addr(), offset, KnownSize::size(ptr)) { return Err(EINVAL); } =20 - // Probably no need to check, since the safety requirements of `Se= lf::new` guarantee that - // this can't overflow. - self.addr().checked_add(offset).ok_or(EINVAL) + let projected_ptr =3D ptr.cast::().wrapping_byte_add(offset); + // SAFETY: `offset_valid` checks for size and alignment and theref= ore `projected_ptr` is a + // valid projection. + Ok(unsafe { Self::Backend::project_view(view, projected_ptr) }) } =20 /// Fallible 8-bit read with runtime bounds check. @@ -376,7 +396,7 @@ fn io_addr(self, offset: usize) -> Result { fn try_read8(self, offset: usize) -> Result where usize: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { self.try_read(offset) } @@ -386,7 +406,7 @@ fn try_read8(self, offset: usize) -> Result fn try_read16(self, offset: usize) -> Result where usize: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { self.try_read(offset) } @@ -396,7 +416,7 @@ fn try_read16(self, offset: usize) -> Result fn try_read32(self, offset: usize) -> Result where usize: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { self.try_read(offset) } @@ -406,7 +426,7 @@ fn try_read32(self, offset: usize) -> Result fn try_read64(self, offset: usize) -> Result where usize: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { self.try_read(offset) } @@ -416,7 +436,7 @@ fn try_read64(self, offset: usize) -> Result fn try_write8(self, value: u8, offset: usize) -> Result where usize: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { self.try_write(offset, value) } @@ -426,7 +446,7 @@ fn try_write8(self, value: u8, offset: usize) -> Result fn try_write16(self, value: u16, offset: usize) -> Result where usize: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { self.try_write(offset, value) } @@ -436,7 +456,7 @@ fn try_write16(self, value: u16, offset: usize) -> Resu= lt fn try_write32(self, value: u32, offset: usize) -> Result where usize: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { self.try_write(offset, value) } @@ -446,7 +466,7 @@ fn try_write32(self, value: u32, offset: usize) -> Resu= lt fn try_write64(self, value: u64, offset: usize) -> Result where usize: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { self.try_write(offset, value) } @@ -456,7 +476,7 @@ fn try_write64(self, value: u64, offset: usize) -> Resu= lt fn read8(self, offset: usize) -> u8 where usize: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { self.read(offset) } @@ -466,7 +486,7 @@ fn read8(self, offset: usize) -> u8 fn read16(self, offset: usize) -> u16 where usize: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { self.read(offset) } @@ -476,7 +496,7 @@ fn read16(self, offset: usize) -> u16 fn read32(self, offset: usize) -> u32 where usize: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { self.read(offset) } @@ -486,7 +506,7 @@ fn read32(self, offset: usize) -> u32 fn read64(self, offset: usize) -> u64 where usize: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { self.read(offset) } @@ -496,7 +516,7 @@ fn read64(self, offset: usize) -> u64 fn write8(self, value: u8, offset: usize) where usize: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { self.write(offset, value) } @@ -506,7 +526,7 @@ fn write8(self, value: u8, offset: usize) fn write16(self, value: u16, offset: usize) where usize: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { self.write(offset, value) } @@ -516,7 +536,7 @@ fn write16(self, value: u16, offset: usize) fn write32(self, value: u32, offset: usize) where usize: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { self.write(offset, value) } @@ -526,7 +546,7 @@ fn write32(self, value: u32, offset: usize) fn write64(self, value: u64, offset: usize) where usize: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { self.write(offset, value) } @@ -558,12 +578,10 @@ fn write64(self, value: u64, offset: usize) fn try_read(self, location: L) -> Result where L: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { - let address =3D self.io_addr::(location.offset())?; - - // SAFETY: `address` has been validated by `io_addr`. - Ok(unsafe { self.io_read(address) }.into()) + let view =3D self.io_addr::(location.offset())?; + Ok(Self::Backend::io_read(view).into()) } =20 /// Generic fallible write with runtime bounds check. @@ -593,14 +611,11 @@ fn try_read(self, location: L) -> Result fn try_write(self, location: L, value: T) -> Result where L: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { - let address =3D self.io_addr::(location.offset())?; + let view =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) } - + Self::Backend::io_write(view, io_value); Ok(()) } =20 @@ -641,7 +656,7 @@ fn try_write_reg(self, value: V) -> Result where L: IoLoc, V: LocatedRegister, - Self: IoCapable, + Self::Backend: IoCapable, { let (location, value) =3D value.into_io_op(); =20 @@ -674,17 +689,14 @@ fn try_write_reg(self, value: V) -> Result fn try_update(self, location: L, f: F) -> Result where L: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, F: FnOnce(T) -> T, { - let address =3D self.io_addr::(location.offset())?; + let view =3D self.io_addr::(location.offset())?; =20 - // SAFETY: `address` has been validated by `io_addr`. - let value: T =3D unsafe { self.io_read(address) }.into(); + let value: T =3D Self::Backend::io_read(view).into(); let io_value =3D f(value).into(); - - // SAFETY: `address` has been validated by `io_addr`. - unsafe { self.io_write(io_value, address) } + Self::Backend::io_write(view, io_value); =20 Ok(()) } @@ -714,12 +726,10 @@ fn try_update(self, location: L, f: F) -> Re= sult fn read(self, location: L) -> T where L: IoLoc, - Self: IoCapable, + Self::Backend: 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() + let view =3D self.io_addr_assert::(location.offset()); + Self::Backend::io_read(view).into() } =20 /// Generic infallible write with compile-time bounds check. @@ -747,13 +757,11 @@ fn read(self, location: L) -> T fn write(self, location: L, value: T) where L: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, { - let address =3D self.io_addr_assert::(location.offset()= ); + let view =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) } + Self::Backend::io_write(view, io_value); } =20 /// Generic infallible write of a fully-located register value. @@ -792,7 +800,7 @@ fn write_reg(self, value: V) where L: IoLoc, V: LocatedRegister, - Self: IoCapable, + Self::Backend: IoCapable, { let (location, value) =3D value.into_io_op(); =20 @@ -825,17 +833,13 @@ fn write_reg(self, value: V) fn update(self, location: L, f: F) where L: IoLoc, - Self: IoCapable, + Self::Backend: IoCapable, 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 view =3D self.io_addr_assert::(location.offset()); + let value: T =3D Self::Backend::io_read(view).into(); let io_value =3D f(value).into(); - - // SAFETY: `address` has been validated by `io_addr_assert`. - unsafe { self.io_write(io_value, address) } + Self::Backend::io_write(view, io_value); } } =20 @@ -879,78 +883,76 @@ unsafe impl Send for Mmio<'_, T> {} // SAFETY: `Mmio<'_, T>` is conceptually `&T` but in I/O memory. unsafe impl Sync for Mmio<'_, T> {} =20 -impl Io for Mmio<'_, T> { +impl<'a, T: ?Sized + KnownSize> Io<'a> for Mmio<'a, T> { + type Backend =3D MmioBackend; type Target =3D T; =20 #[inline] - fn addr(self) -> usize { - self.ptr.addr() + fn as_view(self) -> Mmio<'a, T> { + self } +} + +/// I/O Backend for memory-mapped I/O. +pub struct MmioBackend; + +impl IoBackend for MmioBackend { + type View<'a, T: ?Sized + KnownSize> =3D Mmio<'a, T>; =20 #[inline] - fn maxsize(self) -> usize { - KnownSize::size(self.ptr) + fn as_ptr<'a, T: ?Sized + KnownSize>(view: Self::View<'a, T>) -> *mut = T { + view.ptr + } + + #[inline] + unsafe fn project_view<'a, T: ?Sized + KnownSize, U: ?Sized + KnownSiz= e>( + _view: Self::View<'a, T>, + ptr: *mut U, + ) -> Self::View<'a, U> { + // INVARIANT: Per safety requirement, `ptr` is projection from `vi= ew`, so it is also a valid + // memory-mapped I/O region. + Mmio { + ptr, + phantom: PhantomData, + } } } =20 -/// Implements [`IoCapable`] on `$mmio` for `$ty` using `$read_fn` and `$w= rite_fn`. +/// Implements [`IoCapable`] on `$backend` for `$ty` using `$read_fn` and = `$write_fn`. macro_rules! impl_mmio_io_capable { - ($mmio:ident, $(#[$attr:meta])* $ty:ty, $read_fn:ident, $write_fn:iden= t) =3D> { - $(#[$attr])* - impl IoCapable<$ty> for $mmio<'_, T> { + ($backend: ident, $ty:ty, $read_fn:ident, $write_fn:ident) =3D> { + impl IoCapable<$ty> for $backend { #[inline] - unsafe fn io_read(self, address: usize) -> $ty { - // SAFETY: By the trait invariant `address` is a valid add= ress for MMIO operations. - unsafe { bindings::$read_fn(address as *const c_void) } + fn io_read(view: <$backend as IoBackend>::View<'_, $ty>) -> $t= y { + // SAFETY: By the type invariant, `view.ptr` is a valid ad= dress for MMIO operations. + unsafe { bindings::$read_fn(view.ptr.cast_const().cast()) } } =20 #[inline] - unsafe fn io_write(self, value: $ty, address: usize) { - // SAFETY: By the trait invariant `address` is a valid add= ress for MMIO operations. - unsafe { bindings::$write_fn(value, address as *mut c_void= ) } + fn io_write(view: <$backend as IoBackend>::View<'_, $ty>, valu= e: $ty) { + // SAFETY: By the type invariant, `view.ptr` is a valid ad= dress for MMIO operations. + unsafe { bindings::$write_fn(value, view.ptr.cast()) } } } }; } =20 // MMIO regions support 8, 16, and 32-bit accesses. -impl_mmio_io_capable!(Mmio, u8, readb, writeb); -impl_mmio_io_capable!(Mmio, u16, readw, writew); -impl_mmio_io_capable!(Mmio, u32, readl, writel); +impl_mmio_io_capable!(MmioBackend, u8, readb, writeb); +impl_mmio_io_capable!(MmioBackend, u16, readw, writew); +impl_mmio_io_capable!(MmioBackend, u32, readl, writel); // MMIO regions on 64-bit systems also support 64-bit accesses. #[cfg(CONFIG_64BIT)] -impl_mmio_io_capable!(Mmio, u64, readq, writeq); +impl_mmio_io_capable!(MmioBackend, u64, readq, writeq); =20 -impl<'a, const SIZE: usize> Io for &'a MmioOwned { +impl<'a, const SIZE: usize> Io<'a> for &'a MmioOwned { + type Backend =3D MmioBackend; type Target =3D Region; =20 - /// Returns the base address of this mapping. #[inline] - fn addr(self) -> usize { - self.0.addr() - } - - /// Returns the maximum size of this mapping. - #[inline] - fn maxsize(self) -> usize { - self.0.size() - } -} - -impl<'a, const SIZE: usize, T> IoCapable for &'a MmioOwned -where - Mmio<'a, Region>: IoCapable, -{ - #[inline] - unsafe fn io_read(self, address: usize) -> T { - // SAFETY: Per safety requirement. - unsafe { self.as_view().io_read(address) } - } - - #[inline] - unsafe fn io_write(self, value: T, address: usize) { - // SAFETY: Per safety requirement. - unsafe { self.as_view().io_write(value, address) } + fn as_view(self) -> Mmio<'a, Self::Target> { + // SAFETY: `Mmio` has same invariant as `MmioOwned` + unsafe { Mmio::from_raw(self.0) } } } =20 @@ -966,13 +968,6 @@ pub unsafe fn from_raw(raw: &MmioRaw>) ->= &Self { // SAFETY: `MmioOwned` is a transparent wrapper around `MmioRaw`. unsafe { &*core::ptr::from_ref(raw).cast() } } - - /// Return a view that covers the full region. - #[inline] - pub fn as_view(&self) -> Mmio<'_, Region> { - // SAFETY: `Mmio` has same invariant as `MmioOwned`. - unsafe { Mmio::from_raw(self.0) } - } } =20 /// [`Mmio`] but using relaxed accessors. @@ -1004,17 +999,38 @@ unsafe impl Send for RelaxedMmio<'= _, T> {} // SAFETY: `RelaxedMmio<'_, T>` is conceptually `&T` but in I/O memory. unsafe impl Sync for RelaxedMmio<'_, T> {} =20 -impl Io for RelaxedMmio<'_, T> { - type Target =3D T; +/// I/O Backend for memory-mapped I/O, with relaxed access semantics. +pub struct RelaxedMmioBackend; + +impl IoBackend for RelaxedMmioBackend { + type View<'a, T: ?Sized + KnownSize> =3D RelaxedMmio<'a, T>; =20 #[inline] - fn addr(self) -> usize { - self.ptr.addr() + fn as_ptr<'a, T: ?Sized + KnownSize>(view: Self::View<'a, T>) -> *mut = T { + view.ptr } =20 #[inline] - fn maxsize(self) -> usize { - KnownSize::size(self.ptr) + unsafe fn project_view<'a, T: ?Sized + KnownSize, U: ?Sized + KnownSiz= e>( + _view: Self::View<'a, T>, + ptr: *mut U, + ) -> Self::View<'a, U> { + // INVARIANT: Per safety requirement, `ptr` is projection from `vi= ew`, so it is also a valid + // memory-mapped I/O region. + RelaxedMmio { + ptr, + phantom: PhantomData, + } + } +} + +impl<'a, T: ?Sized + KnownSize> Io<'a> for RelaxedMmio<'a, T> { + type Backend =3D RelaxedMmioBackend; + type Target =3D T; + + #[inline] + fn as_view(self) -> RelaxedMmio<'a, T> { + self } } =20 @@ -1051,14 +1067,9 @@ pub fn relaxed(self) -> RelaxedMmio<'a, T> { } =20 // MMIO regions support 8, 16, and 32-bit accesses. -impl_mmio_io_capable!(RelaxedMmio, u8, readb_relaxed, writeb_relaxed); -impl_mmio_io_capable!(RelaxedMmio, u16, readw_relaxed, writew_relaxed); -impl_mmio_io_capable!(RelaxedMmio, u32, readl_relaxed, writel_relaxed); +impl_mmio_io_capable!(RelaxedMmioBackend, u8, readb_relaxed, writeb_relaxe= d); +impl_mmio_io_capable!(RelaxedMmioBackend, u16, readw_relaxed, writew_relax= ed); +impl_mmio_io_capable!(RelaxedMmioBackend, u32, readl_relaxed, writel_relax= ed); // MMIO regions on 64-bit systems also support 64-bit accesses. -impl_mmio_io_capable!( - RelaxedMmio, - #[cfg(CONFIG_64BIT)] - u64, - readq_relaxed, - writeq_relaxed -); +#[cfg(CONFIG_64BIT)] +impl_mmio_io_capable!(RelaxedMmioBackend, u64, readq_relaxed, writeq_relax= ed); diff --git a/rust/kernel/pci/io.rs b/rust/kernel/pci/io.rs index 89f4bb483a7f..e67c1e3694fb 100644 --- a/rust/kernel/pci/io.rs +++ b/rust/kernel/pci/io.rs @@ -9,6 +9,7 @@ devres::Devres, io::{ Io, + IoBackend, IoCapable, MmioOwned, MmioRaw, @@ -84,32 +85,57 @@ unsafe impl Send for ConfigSpace<'_, = T> {} // SAFETY: `ConfigSpace<'_, T>` is conceptually `&T` but in I/O memory. unsafe impl Sync for ConfigSpace<'_, T> {} =20 +/// I/O Backend for PCI configuration space. +pub struct ConfigSpaceBackend; + +impl IoBackend for ConfigSpaceBackend { + type View<'a, T: ?Sized + KnownSize> =3D ConfigSpace<'a, T>; + + #[inline] + fn as_ptr<'a, T: ?Sized + KnownSize>(view: ConfigSpace<'a, T>) -> *mut= T { + view.ptr + } + + #[inline] + unsafe fn project_view<'a, T: ?Sized + KnownSize, U: ?Sized + KnownSiz= e>( + view: Self::View<'a, T>, + ptr: *mut U, + ) -> Self::View<'a, U> { + // INVARIANT: Per safety requirement. + ConfigSpace { + pdev: view.pdev, + ptr, + } + } +} + /// Implements [`IoCapable`] on [`ConfigSpace`] for `$ty` using `$read_fn`= and `$write_fn`. macro_rules! impl_config_space_io_capable { ($ty:ty, $read_fn:ident, $write_fn:ident) =3D> { - impl<'a, T: ?Sized> IoCapable<$ty> for ConfigSpace<'a, T> { - unsafe fn io_read(self, address: usize) -> $ty { + impl IoCapable<$ty> for ConfigSpaceBackend { + fn io_read(view: ConfigSpace<'_, $ty>) -> $ty { + // CAST: The offset is cast to `i32` because the C functio= ns expect a 32-bit + // signed offset parameter. PCI configuration space size i= s at most 4096 bytes, + // so the value always fits within `i32` without truncatio= n or sign change. + let addr =3D view.ptr.addr() as i32; + let mut val: $ty =3D 0; =20 // Return value from C function is ignored in infallible a= ccessors. - let _ret =3D - // SAFETY: By the type invariant `self.pdev` is a vali= d address. - // CAST: The offset is cast to `i32` because the C fun= ctions expect a 32-bit - // signed offset parameter. PCI configuration space si= ze is at most 4096 bytes, - // so the value always fits within `i32` without trunc= ation or sign change. - unsafe { bindings::$read_fn(self.pdev.as_raw(), addres= s as i32, &mut val) }; - + // SAFETY: By the type invariant `pdev` is a valid address. + let _ =3D unsafe { bindings::$read_fn(view.pdev.as_raw(), = addr, &mut val) }; val } =20 - unsafe fn io_write(self, value: $ty, address: usize) { + fn io_write(view: ConfigSpace<'_, $ty>, value: $ty) { + // CAST: The offset is cast to `i32` because the C functio= ns expect a 32-bit + // signed offset parameter. PCI configuration space size i= s at most 4096 bytes, + // so the value always fits within `i32` without truncatio= n or sign change. + let addr =3D view.ptr.addr() as i32; + // Return value from C function is ignored in infallible a= ccessors. - let _ret =3D - // SAFETY: By the type invariant `self.pdev` is a vali= d address. - // CAST: The offset is cast to `i32` because the C fun= ctions expect a 32-bit - // signed offset parameter. PCI configuration space si= ze is at most 4096 bytes, - // so the value always fits within `i32` without trunc= ation or sign change. - unsafe { bindings::$write_fn(self.pdev.as_raw(), addre= ss as i32, value) }; + // SAFETY: By the type invariant `pdev` is a valid address. + let _ =3D unsafe { bindings::$write_fn(view.pdev.as_raw(),= addr, value) }; } } }; @@ -120,17 +146,13 @@ unsafe fn io_write(self, value: $ty, address: usize) { impl_config_space_io_capable!(u16, pci_read_config_word, pci_write_config_= word); impl_config_space_io_capable!(u32, pci_read_config_dword, pci_write_config= _dword); =20 -impl<'a, T: ?Sized + KnownSize> Io for ConfigSpace<'a, T> { +impl<'a, T: ?Sized + KnownSize> Io<'a> for ConfigSpace<'a, T> { + type Backend =3D ConfigSpaceBackend; type Target =3D T; =20 #[inline] - fn addr(self) -> usize { - self.ptr.addr() - } - - #[inline] - fn maxsize(self) -> usize { - KnownSize::size(self.ptr) + fn as_view(self) -> ConfigSpace<'a, T> { + self } } =20 --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from CWXP265CU010.outbound.protection.outlook.com (mail-ukwestazon11022126.outbound.protection.outlook.com [52.101.101.126]) (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 B757A441030; Thu, 11 Jun 2026 16:28:37 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.101.126 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195320; cv=fail; b=k3kab3N2CIhqW9uUlU3qJkdJmEZmS6j0lWvYAGmELn8Ur0m5PpvoTy+riMFPGIRUZ8Pu1qIGs7P1zY6Sj/8gsJgK2kYKoh9V0kNGmca7ZGjXYJzirHgvk9NI5BBnz73xSPeEFJgHyDa4/BZJCEPcgspdD4dFombHh0SQvmMnMdo= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195320; c=relaxed/simple; bh=iK6UgmiaN9Jcnn8xAl/Gjs2DlE8eXQgL6Hxf/lSxxFo=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=AQVctUxkbGBq9nc/XhaITcRGC97Fu2dIvLKrP+9X7l+8pSwbSLGSbQR+0nP12YLZi3Muw3h6oqFL3BVSYEE43wRxrHyFql1bCOCI558ONeko96bQBHtMNhecm5mowUQB7tOYFUi/6YA5spstuhsYKhXk62izpezByLjFobveKwk= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=G5W3uHWX; arc=fail smtp.client-ip=52.101.101.126 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="G5W3uHWX" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=nmxLX+pa+v7bxdhmm2s3WG6UsJHdY/XIEd1+XyDOtMLxAKcYh155FyCOgW63MlTXizD2Wm/zyU72HIr28wcjUS8jHpj9veirkEWWE9+5j4A/NkJ29QObXiDhLYrg4yiDWSUGujsS4QZ/UT1AmKSzCQCr6mfGXrdvcJagYOSS2vMAxVxY8FpBdqCFB65XQ1iP4J9WD8GmKmZOugoPrgyZHQNOjHmbcO04SEl9VwsXS3sFN1DYlXsk5eQ+ZZhPls4sE0TeO5BOsfsPjZXumk+yRVweSM9CJNMGzT9eD5I5ZzKW94JzSsVw/s/fdh3hyL7eVBfw1SXU88BiuNOkbhIwrQ== 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=O+f600/3NgUVIUQ4CUqf5OEvw/H8USpLP5zT8BXesqU=; b=oDhyh1k3BIuH9DTBQWU4uNIp8DSFnMJLCEQVVUJ8vJvCeKWabMU2LhD3OUqsTau15y7vLcFJftB5wyteTjjAQJaLleHrHF0FahWSMRdQdWR+j4MEFEfPjXA1ILqV0eUZiZg6qzr7B8otKK3zXFNdMaMoadt47kjEOUVgOMKfVfyLuIeeLbezyp8bbYtAmnN8h/DKO2DQi45pJuLy2EKsgu7iQ0jH+gD66RFjzrMqoJsx+ClKv8YnGEGKpM1z75xaJi7GpZFl63gmL8KVCq671VxTSrnIOjvPB9GHSuAMPMZyiIJit4hQqHqmFooPBM/yGxTdaLVhnjL6IqFQKBHZmg== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=O+f600/3NgUVIUQ4CUqf5OEvw/H8USpLP5zT8BXesqU=; b=G5W3uHWXpjn7/1EmMSmKjw+bjb/Zq4Y8hX2deAbmstiEbCSlb08OA5hnbDSeTsQWFWxUJesVWn3qhOmjQR15IoQsteSkLMpZH4pqOYgfrok3zvMzkpFLFzRVNVLphwXSwOv0Tge35Hte6FnuTkv3RX9BJUkAiM9TO0YC1/NX8dM= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO4P265MB6525.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:2e7::9) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.11; Thu, 11 Jun 2026 16:28:28 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:28 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:12 +0100 Subject: [PATCH v4 10/20] rust: io: remove `MmioOwned` Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-10-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195301; l=8853; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=iK6UgmiaN9Jcnn8xAl/Gjs2DlE8eXQgL6Hxf/lSxxFo=; b=o2LFKxdITrV8B3IlCdPP4CTRc+MdH0hNCxvLG8d7SwllaV5yZP4V7DiP8ow11fSLPcvigEaE1 3o0/ryTWPr2DdZBKamJlxT87i4DafUSk4XT+tDUgsV1VeYK6MkYZDhw X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO4P265MB6525:EE_ X-MS-Office365-Filtering-Correlation-Id: 985a4382-ac92-4a6f-c1f8-08dec7d67813 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|23010399003|376014|7416014|366016|1800799024|10070799003|921020|6133799003|56012099006|5023799004|22082099003|18002099003; X-Microsoft-Antispam-Message-Info: g5ZWzC4aGGIHBBcvUO/FC3xRtHmQpNphNe8bfl307iEeG7SOtDTX9JsEZ3Q2k5Kp409ZefMLRHjEhTxaMCqB4ZVH1nA81FtWklpJnrpLNaIyq0aLArTebHLBQ3ILj198Iy4LxdhA1zY/hizVZlmsFktd9RYmyy5qlHl/5j4rM7zNdn3FxBx94lvULog0b/CR29Bpdsyii/YDl4Egcp8hZ0yMcRxlrOOxZooOwjET6Uaf/WO/flAJRkMU0DrWSErmqsVz2C7BZQLEpN4i9DvmU3GQo6EW2r6gvoYDmqE9JgTeYSh4V2ln+0Bh9CRX/QNQhjCHQXf16xAkhwQMROKI7xBKZ2kQGirxU4kAqM6ymFUcFM+6y32i3PLsUo3zQeOiCH7h1YJhdmXT9ra/vd743ZBRLyEs6MYqufIbvgxD8A+lyD79zTv9CFCAjghEYOdnxDHPY7YMXocRKmHoiLDPMGsVcA7B09H0OE+9EWohToOWXDJYX+h+cbErGVMbwVrPyEZ6O41fPbVrqY7Lczby5iCLFwb+rCLxEOPynw8R6XPS4jvGeOluHOGfUeHNUOTXtmFKB3dIpSqZX0v6MYkdxfC9RoIyrolX4Kc8w3p65vLYZgjX56abtasejq+rHiRn+1YcCFYzeeyAAVQSdEMVuuhjABy88SU4nKMvoU1gZdd0ahDFI/+KzSpr+SU2CiCKgzxVVSfqqZFyWIaJTjWyDkyR6v05w7ZL/KRk1WSQxKk= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(23010399003)(376014)(7416014)(366016)(1800799024)(10070799003)(921020)(6133799003)(56012099006)(5023799004)(22082099003)(18002099003);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?eXNnS0l6LzdKdmVRN3lhdnZFZjcvWmxCbmJRb2RWWlU1bmpKUmFORDRhVzl6?= =?utf-8?B?SDE0UC96MDVCMDF2NmxmMU1udjBjR0IyenNVeU9NcHMreWp3eWdUazBqNEl0?= =?utf-8?B?empRVHFZenFpckRtQWthZUpqVnp2dEE1bXhTVW5UNVZWVTB2OEY1TS9aNWcv?= =?utf-8?B?Y1ZDdzNBalF3dWk2YkhlR3U5aWpWbTdmYUxCbUhoM2hGZU9ydHlNZGswNzlV?= =?utf-8?B?SVh5bjlGR2ZjWUg5a2o0amMxWE9vdHJVTlp6UDBUYm1NaUJPOHI3MEY2VkE4?= =?utf-8?B?bjJ4ZkZNUU9qSnJTcnd4ZU5ZTHNpRmU5K0xNRGQ2VVg4QlhzZXZHTEZPYXpK?= =?utf-8?B?bFF3SkxCTjlWMW9rR1JpZVlYSUpYd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UlhvUW8xQ0oxbklLUVEveEdRaUZYd2h0UEhOclBSMVcw?= =?utf-8?B?dFlSRk9QV1RHVE16VnpEK2ZQV1pMZTREb0UwQ1BuVFVEdUlGcU45VlhsbW02?= =?utf-8?B?SmlMSE9ydWhnakdqUTJmSnB4eUx0bkVkREtVWHNtUUhnRlMwYmVpUT09?= X-OriginatorOrg: garyguo.net X-MS-Exchange-CrossTenant-Network-Message-Id: 985a4382-ac92-4a6f-c1f8-08dec7d67813 X-MS-Exchange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:28.5608 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: 60fPJMLaQK148vunb3RDvVbNgFbFzdLHP376nEEaqrgrw1pzlLiP3vigRfWW6qHkqaXTO4rcph+vr2C/joJUpQ== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO4P265MB6525 `Io` trait is now very easy to implement. Thus, implement it on `Bar` and `IoMem` directly and remove the `MmioOwned` struct. Signed-off-by: Gary Guo Suggested-by: Danilo Krummrich --- rust/kernel/devres.rs | 12 +++--- rust/kernel/io.rs | 103 +---------------------------------------------= ---- rust/kernel/io/mem.rs | 26 +++++++------ rust/kernel/pci/io.rs | 16 ++++---- 4 files changed, 32 insertions(+), 125 deletions(-) diff --git a/rust/kernel/devres.rs b/rust/kernel/devres.rs index aed0c994fd30..3545ffc5345d 100644 --- a/rust/kernel/devres.rs +++ b/rust/kernel/devres.rs @@ -68,8 +68,9 @@ struct Inner { /// devres::Devres, /// io::{ /// Io, -/// MmioOwned, +/// Mmio, /// MmioRaw, +/// MmioBackend, /// PhysAddr, /// Region, // /// }, @@ -104,12 +105,13 @@ struct Inner { /// } /// } /// -/// impl Deref for IoMem { -/// type Target =3D MmioOwned; +/// impl<'a, const SIZE: usize> Io<'a> for &'a IoMem { +/// type Backend =3D MmioBackend; +/// type Target =3D Region; /// -/// fn deref(&self) -> &Self::Target { +/// fn as_view(self) -> Mmio<'a, Region> { /// // SAFETY: The memory range stored in `self` has been properly= mapped in `Self::new`. -/// unsafe { MmioOwned::from_raw(&self.0) } +/// unsafe { Mmio::from_raw(self.0) } /// } /// } /// # fn no_run(dev: &Device) -> Result<(), Error> { diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index e422a5ff2a5e..132454a38d64 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -99,8 +99,8 @@ fn size(p: *const Self) -> usize { /// the represented MMIO region does exist or is properly mapped. /// /// Instead, the bus specific MMIO implementation must convert this raw re= presentation into an -/// `MmioOwned` instance providing the actual memory accessors. Only by th= e conversion into an -/// `MmioOwned` structure any guarantees are given. +/// `Mmio` instance providing the actual memory accessors. Only by the con= version into an `Mmio` +/// structure any guarantees are given. pub struct MmioRaw { /// Pointer is in I/O address space. /// @@ -157,80 +157,6 @@ pub fn size(&self) -> usize { } } =20 -/// IO-mapped memory region. -/// -/// The creator (usually a subsystem / bus such as PCI) is responsible for= creating the -/// mapping, performing an additional region request etc. -/// -/// # Invariant -/// -/// `addr` is the start and `maxsize` the length of valid I/O mapped memor= y region of size -/// `maxsize`. -/// -/// # Examples -/// -/// ```no_run -/// use kernel::{ -/// bindings, -/// ffi::c_void, -/// io::{ -/// Io, -/// MmioOwned, -/// MmioRaw, -/// PhysAddr, -/// Region, -/// }, -/// }; -/// use core::ops::Deref; -/// -/// // See also `pci::Bar` for a real example. -/// struct IoMem(MmioRaw>); -/// -/// impl IoMem { -/// /// # Safety -/// /// -/// /// [`paddr`, `paddr` + `SIZE`) must be a valid MMIO region that i= s mappable into the CPUs -/// /// virtual address space. -/// unsafe fn new(paddr: usize) -> Result{ -/// // SAFETY: By the safety requirements of this function [`paddr= `, `paddr` + `SIZE`) is -/// // valid for `ioremap`. -/// let addr =3D unsafe { bindings::ioremap(paddr as PhysAddr, SIZ= E) }; -/// if addr.is_null() { -/// return Err(ENOMEM); -/// } -/// -/// Ok(IoMem(MmioRaw::new_region(addr as usize, SIZE)?)) -/// } -/// } -/// -/// impl Drop for IoMem { -/// fn drop(&mut self) { -/// // SAFETY: `self.0.addr()` is guaranteed to be properly mapped= by `Self::new`. -/// unsafe { bindings::iounmap(self.0.addr() as *mut c_void); }; -/// } -/// } -/// -/// impl Deref for IoMem { -/// type Target =3D MmioOwned; -/// -/// fn deref(&self) -> &Self::Target { -/// // SAFETY: The memory range stored in `self` has been properly= mapped in `Self::new`. -/// unsafe { MmioOwned::from_raw(&self.0) } -/// } -/// } -/// -///# fn no_run() -> Result<(), Error> { -/// // SAFETY: Invalid usage for example purposes. -/// let iomem =3D unsafe { IoMem::<{ core::mem::size_of::() }>::new(0= xBAAAAAAD)? }; -/// iomem.write32(0x42, 0x0); -/// assert!(iomem.try_write32(0x42, 0x0).is_ok()); -/// assert!(iomem.try_write32(0x42, 0x4).is_err()); -/// # Ok(()) -/// # } -/// ``` -#[repr(transparent)] -pub struct MmioOwned(MmioRaw>); - /// Checks whether an access of type `U` at the given `base` and the given= `offset` /// is valid within this region. /// @@ -945,31 +871,6 @@ fn io_write(view: <$backend as IoBackend>::View<'_, $t= y>, value: $ty) { #[cfg(CONFIG_64BIT)] impl_mmio_io_capable!(MmioBackend, u64, readq, writeq); =20 -impl<'a, const SIZE: usize> Io<'a> for &'a MmioOwned { - type Backend =3D MmioBackend; - type Target =3D Region; - - #[inline] - fn as_view(self) -> Mmio<'a, Self::Target> { - // SAFETY: `Mmio` has same invariant as `MmioOwned` - unsafe { Mmio::from_raw(self.0) } - } -} - -impl MmioOwned { - /// Converts an `MmioRaw` into an `MmioOwned` instance, providing the = accessors to the MMIO - /// mapping. - /// - /// # Safety - /// - /// Callers must ensure that `addr` is the start of a valid I/O mapped= memory region of size - /// `maxsize`. - pub unsafe fn from_raw(raw: &MmioRaw>) -> &Self { - // SAFETY: `MmioOwned` is a transparent wrapper around `MmioRaw`. - unsafe { &*core::ptr::from_ref(raw).cast() } - } -} - /// [`Mmio`] but using relaxed accessors. /// /// This type provides an implementation of [`Io`] that uses relaxed I/O M= MIO operands instead of diff --git a/rust/kernel/io/mem.rs b/rust/kernel/io/mem.rs index 8f6c257c5b8e..d9b3189d09b4 100644 --- a/rust/kernel/io/mem.rs +++ b/rust/kernel/io/mem.rs @@ -2,8 +2,6 @@ =20 //! Generic memory-mapped IO. =20 -use core::ops::Deref; - use crate::{ device::{ Bound, @@ -16,7 +14,9 @@ Region, Resource, // }, - MmioOwned, + Io, + Mmio, + MmioBackend, MmioRaw, // }, prelude::*, @@ -210,11 +210,13 @@ pub fn into_devres(self) -> Result>> { } } =20 -impl Deref for ExclusiveIoMem<'_, SIZE> { - type Target =3D MmioOwned; +impl<'a, const SIZE: usize> Io<'a> for &'a ExclusiveIoMem<'_, SIZE> { + type Backend =3D MmioBackend; + type Target =3D super::Region; =20 - fn deref(&self) -> &Self::Target { - &self.iomem + #[inline] + fn as_view(self) -> Mmio<'a, Self::Target> { + self.iomem.as_view() } } =20 @@ -290,11 +292,13 @@ fn drop(&mut self) { } } =20 -impl Deref for IoMem<'_, SIZE> { - type Target =3D MmioOwned; +impl<'a, const SIZE: usize> Io<'a> for &'a IoMem<'_, SIZE> { + type Backend =3D MmioBackend; + type Target =3D super::Region; =20 - fn deref(&self) -> &Self::Target { + #[inline] + fn as_view(self) -> Mmio<'a, Self::Target> { // SAFETY: Safe as by the invariant of `IoMem`. - unsafe { MmioOwned::from_raw(&self.io) } + unsafe { Mmio::from_raw(self.io) } } } diff --git a/rust/kernel/pci/io.rs b/rust/kernel/pci/io.rs index e67c1e3694fb..4be33ecb4192 100644 --- a/rust/kernel/pci/io.rs +++ b/rust/kernel/pci/io.rs @@ -11,16 +11,14 @@ Io, IoBackend, IoCapable, - MmioOwned, + Mmio, + MmioBackend, MmioRaw, Region, // }, prelude::*, ptr::KnownSize, // }; -use core::{ - ops::Deref, // -}; =20 /// Represents the size of a PCI configuration space. /// @@ -269,12 +267,14 @@ fn drop(&mut self) { } } =20 -impl Deref for Bar<'_, SIZE> { - type Target =3D MmioOwned; +impl<'a, const SIZE: usize> Io<'a> for &'a Bar<'_, SIZE> { + type Backend =3D MmioBackend; + type Target =3D crate::io::Region; =20 - fn deref(&self) -> &Self::Target { + #[inline] + fn as_view(self) -> Mmio<'a, Self::Target> { // SAFETY: By the type invariant of `Self`, the MMIO range in `sel= f.io` is properly mapped. - unsafe { MmioOwned::from_raw(&self.io) } + unsafe { Mmio::from_raw(self.io) } } } =20 --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from CWXP265CU010.outbound.protection.outlook.com (mail-ukwestazon11022106.outbound.protection.outlook.com [52.101.101.106]) (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 8A46D44D6A1; Thu, 11 Jun 2026 16:28:39 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.101.106 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195323; cv=fail; b=UWkrr1aFgHHExiP/FArhYxoRIWTUy3f2nE1OgK02rmUIFPDpWxvHfXalSHI3GjS1uHEw/u6nlopmsGNf8IB45uNqCAvjtJydQghWKXwgl/HEeueTb77yJ2o4A8mpiHBa9zUSW/OjcNkDyXm03X7RL5DJq2jbMC7AB3/9toOaJBo= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195323; c=relaxed/simple; bh=yTxNVoexkQa5ghSRgiZ4IDZUMzahHs98bJoJqFesjDg=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=dBlfVmMXKJXl9Qcn2TlR45b6xUtWRS5GhfFd07d/QlCT48bwMXc04juhLF6vTwHz60O30lY9nGm9JBwRQO/B1E8p7EXnw0xzvkXmhg8d5lgc5lM9NL65c8ukdwS6WCerDgiE8wV/bn9epne2Se924dNfKk4IGGRPcPOPyCMXrlQ= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=zzwx/o72; arc=fail smtp.client-ip=52.101.101.106 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="zzwx/o72" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=oDdwgxLnMYi3UICnXrhxn7Ji5gCxd3JJNf+YAuMowpVs6wav7/gnW6sgqCg71hdwiwmd74ubXMppy2OZHYO1T7jOMXtACXUtIqPW1KY3lT1p3Kvrc9X6c3HehEbvae8gPC730mFXPGgAGdLqMPakClKvVKtJ2TZdoYF1YsQ4sAQUf8TznYchaMdX7Q05ENgrRDzUQcOcxYx3uN0ASuVI7kNUgSwjR3z9gD8XRFQkaal4/ngqNEPfDjNbR1Wq0oFjf2pDZskqbzJUT2pf6HRW4qYPTuXbRoL5MAppUHAabY/2H7N9cx4vDaIwKDR0a9Hw+7skGNYjYmhH966Gi6x/Xg== 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=CU3aq4g1wJ41mMYj2EqQEpAh/FCh6owb2V+lttrlG+I=; b=gLUUb6WyQ8pRKnV/fsRzYDnmfj0VYC95PKhL7/6ebQuVqG/yoZLf0bLgMOpxRQKIzzEXJzbx20iM3DlKv+DkibNtlrT/ReU8hcdxWTp1c3fUqUDEc9HiPngoI6ud8pv+8nG1ojZ9OFkfodJjJtjoa17hLwq12gVDceuQnQvthQ4zI54umhSK2Z5ipcmw07aUcNyxtsJmC/+ffdcP06aOKhf5Jc2On/LfVKFU5/8Jfcmf5pHj+gYWOLej8zmOjQY8AKkXMlFGBNtonp9LEmkOyfCuJ5B/iVCTjjGuv5NJTSytj2kGn1W2vTA08J4IMy+nUD4O/PAC6Bfkhfp3pc6meQ== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=CU3aq4g1wJ41mMYj2EqQEpAh/FCh6owb2V+lttrlG+I=; b=zzwx/o72edDVPcxJzHhPNytJIEKRH1EnPq/VIi411C8Ze0zn9/JyM8bBNZ1SfePcqE14XefI4IEmn0MDUZYrtpfe9/UYZ9kFD/eKZHnwGsVU+7F/WbD/a+WkMth0RfxHUWoccLzKONU2Uh1l/f6jvU1z15J423ypQ/6GSQUbydg= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO4P265MB6525.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:2e7::9) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.11; Thu, 11 Jun 2026 16:28:29 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:29 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:13 +0100 Subject: [PATCH v4 11/20] rust: io: move `Io` methods to extension trait Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-11-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195301; l=6959; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=yTxNVoexkQa5ghSRgiZ4IDZUMzahHs98bJoJqFesjDg=; b=GG6s4jjIT1Nfjs3VO1gdInRVylFCHg0hKlxdTWHcNVVbcjGdjZ4icmjasx+yHiUPKHeyNSuCb ww9057mJqs0AubGbWTyrg0FAdgAjBAXJxndqvSFvQ7sZhR1l3oZgSyJ X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO4P265MB6525:EE_ X-MS-Office365-Filtering-Correlation-Id: 51f334b6-df05-4dd3-46ba-08dec7d67872 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|23010399003|376014|7416014|366016|1800799024|10070799003|921020|6133799003|56012099006|3023799007|5023799004|22082099003|18002099003; X-Microsoft-Antispam-Message-Info: vks86nwaePNnp2ERbdmQqhxC+6QczAJtM1q9XZXA3LF4f+v+aEF0GSwz7ySXmjCYna1eeo/ZYGO4wpNwg97vI8w1HJ2TZ3RmWSAYkifs0ZYCCESxsp8vpMLrnbBVLGcw/AIf6dSHg0Es7dqx3ZTPzXCztRK2f/5fJgPNFJxPqgptgYxWEdFFdZBR5ydt/ljdtede2PNlrA7YivgJHpASxqONXYzAJ9VtFxnl/GRUU1aFY/s/0hgUu57os2VuQcpY/eHngMlqg6jenygnbF+VhdYcn5jDd9NHCOA/x4GeegazDfWbtY5mMA0l99UHiLu12P42QtXnUojTm340gFzNRhnGjFeW0+SI/HKvadYGjDgA805yhOUXeD6rrHeeMPTBLlY4buobngP6x3yR4QgThBJ+wzlQSoH19Vb9tDq3s8Tc/DSEkBpNP1jW3dR/zNAl2QGMmZlvbxuLJ87zc1j7Vjd0tQvwlUMydcGy2uQXDNZ4c0FKNNlUOPB2xw7/zh2/jv5h7ip+YeStd3EGcogvpxMukq+r7SMqB3sOXLeTclwt0QhPmO1u3+v1kCdo2wr5e8C2us1+BUPxZmHFGiyC8n494NfqQAEE2zUHz3D5vwFfzfoFq5IBVNXd9Ydd4jOEvk/thC57Q7D1eRfTK04le9xAZSYcl5amgphFAk/44kfCjFGv9ZelqaM5HzKVi7S8Qd17kwuJ4RnrfBCrMfZyhYEFjolFH3L9CwF/GNCaVeM= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(23010399003)(376014)(7416014)(366016)(1800799024)(10070799003)(921020)(6133799003)(56012099006)(3023799007)(5023799004)(22082099003)(18002099003);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?ZFlzOVpXSTcrZFN6UXNObFhvOEJGdnh1MEUwdHRUMzVJZVhramZQSHlQZU9E?= =?utf-8?B?Ui8zbFo4NEtOZ0lZMVFWWk14cFVOWndFV1dXNFFXTEUwZ050R0dUV3FVeFkv?= =?utf-8?B?SEg2ZFVSMGx1bEd4U1VwNTVHRTM0c3VTalUvUDlaWkd4N3ZhU1hzNC93YnZ4?= =?utf-8?B?MHJFT3l1eTdPR3BWMmQ0QllTWlplcWI1WFZwSG9tNmo2anJSOGF5T1VucjM1?= =?utf-8?B?bXJiemdWZGkyUzBJQVlHZzJGR2RjWGp2NVhleWhHaVVzMUlDcHpVVnpxRExu?= =?utf-8?B?L0hxSDdTd1hsdTZSdEt6MVdEZUIxL0Y5bEx1TnZXWENOMmUyaHo2VDVsdDVm?= =?utf-8?B?Zy9hWklhUFh5b2VDcnRkYnFIR2hBcGFLcUxrNThlNitwSTNNdWRoRFlEQ1hP?= =?utf-8?B?eDdITlFKNnd2QU5PNU9ubGh5Zmh3cW1BbWo2MnhWV0dKL3g3TnhZWnJyR2ls?= =?utf-8?B?OUZWU2t3dkVaNFVUak96anBwQ0hQNVZIMU83Z0dycTRQSmduckovRFgzbFJh?= =?utf-8?B?ZXc3aE00MUJLTHE2dUZ3aVUzdHVJZHhZWnpEN3l6Vm9VTmNUMU9iNDJGOXRk?= =?utf-8?B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05-4dd3-46ba-08dec7d67872 X-MS-Exchange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:29.1653 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: fnxQK+k/vbFzg5MgSFKqu34E3ahZXGQB+1SQy3NAjcAbB5VYC+6T3v/RrSav5tYREOdYKpSra2S2hetxzmz0Dw== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO4P265MB6525 `Io` trait now has a single required methods with many more provided methods. Provided methods may want to rely on their implementations to not be arbitrarily overridden by implementers for correctness or soundness. Thus, extract these methods to a new trait and provide a blanket implementation. This pattern is used extensively in userspace Rust libraries e.g. `tokio` where `AsyncRead` has minimum methods and `AsyncReadExt` is what users mostly interact with. To avoid changing all user imports, the base trait is renamed to `IoBase` and the newly added trait takes the existing `Io` name. A `size` method is added as an example of methods that users should not override. Suggested-by: Danilo Krummrich Signed-off-by: Gary Guo --- rust/kernel/devres.rs | 3 ++- rust/kernel/io.rs | 34 ++++++++++++++++++++++++---------- rust/kernel/io/mem.rs | 6 +++--- rust/kernel/pci/io.rs | 6 +++--- 4 files changed, 32 insertions(+), 17 deletions(-) diff --git a/rust/kernel/devres.rs b/rust/kernel/devres.rs index 3545ffc5345d..6e0b845b229b 100644 --- a/rust/kernel/devres.rs +++ b/rust/kernel/devres.rs @@ -68,6 +68,7 @@ struct Inner { /// devres::Devres, /// io::{ /// Io, +/// IoBase, /// Mmio, /// MmioRaw, /// MmioBackend, @@ -105,7 +106,7 @@ struct Inner { /// } /// } /// -/// impl<'a, const SIZE: usize> Io<'a> for &'a IoMem { +/// impl<'a, const SIZE: usize> IoBase<'a> for &'a IoMem { /// type Backend =3D MmioBackend; /// type Target =3D Region; /// diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index 132454a38d64..470ee2ed9849 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -184,7 +184,7 @@ const fn offset_valid(base: usize, offset: usize, si= ze: usize) -> bool { /// operation. pub trait IoBackend { /// View type for this I/O backend. - type View<'a, T: ?Sized + KnownSize>: Io<'a, Backend =3D Self, Target = =3D T>; + type View<'a, T: ?Sized + KnownSize>: IoBase<'a, Backend =3D Self, Tar= get =3D T>; =20 /// Convert a `view` to a raw pointer for projection. fn as_ptr<'a, T: ?Sized + KnownSize>(view: Self::View<'a, T>) -> *mut = T; @@ -267,13 +267,10 @@ 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. /// -/// The [`Io`] trait provides: -/// - Method to convert into [`IoBackend::View`]. -/// - Helper methods for offset validation and address calculation -/// - Fallible (runtime checked) accessors for different data widths -/// -/// Which I/O methods are available depends on the associated [`IoBackend`= ] implementation. -pub trait Io<'a>: Copy { +/// This trait defines which backend shall be used for I/O operations and = provides a method to +/// convert into [`IoBackend::View`]. Users should use the [`Io`] trait wh= ich provides the actual +/// methods to perform I/O operations. +pub trait IoBase<'a>: Copy { /// Type that defines all I/O operations. type Backend: IoBackend; =20 @@ -282,6 +279,21 @@ pub trait Io<'a>: Copy { =20 /// Return a view that covers the full region. fn as_view(self) -> ::View<'a, Self::Targe= t>; +} + +/// Extension trait to provide I/O operation methods to types that impleme= nt [`IoBase`]. +/// +/// This trait provides: +/// - Helper methods for offset validation and address calculation +/// - Fallible (runtime checked) accessors for different data widths +/// +/// Which I/O methods are available depends on the associated [`IoBackend`= ] implementation. +pub trait Io<'a>: IoBase<'a> { + /// Returns the size of this I/O region. + #[inline] + fn size(self) -> usize { + KnownSize::size(Self::Backend::as_ptr(self.as_view())) + } =20 /// Returns a view for a given `offset`, performing compile-time bound= checks. // Always inline to optimize out error path of `build_assert`. @@ -769,6 +781,8 @@ fn update(self, location: L, f: F) } } =20 +impl<'a, T: IoBase<'a>> Io<'a> for T {} + /// A view of memory-mapped I/O region. /// /// # Invariant @@ -809,7 +823,7 @@ unsafe impl Send for Mmio<'_, T> {} // SAFETY: `Mmio<'_, T>` is conceptually `&T` but in I/O memory. unsafe impl Sync for Mmio<'_, T> {} =20 -impl<'a, T: ?Sized + KnownSize> Io<'a> for Mmio<'a, T> { +impl<'a, T: ?Sized + KnownSize> IoBase<'a> for Mmio<'a, T> { type Backend =3D MmioBackend; type Target =3D T; =20 @@ -925,7 +939,7 @@ unsafe fn project_view<'a, T: ?Sized + KnownSize, U: ?S= ized + KnownSize>( } } =20 -impl<'a, T: ?Sized + KnownSize> Io<'a> for RelaxedMmio<'a, T> { +impl<'a, T: ?Sized + KnownSize> IoBase<'a> for RelaxedMmio<'a, T> { type Backend =3D RelaxedMmioBackend; type Target =3D T; =20 diff --git a/rust/kernel/io/mem.rs b/rust/kernel/io/mem.rs index d9b3189d09b4..e95b769ebe47 100644 --- a/rust/kernel/io/mem.rs +++ b/rust/kernel/io/mem.rs @@ -14,7 +14,7 @@ Region, Resource, // }, - Io, + IoBase, Mmio, MmioBackend, MmioRaw, // @@ -210,7 +210,7 @@ pub fn into_devres(self) -> Result>> { } } =20 -impl<'a, const SIZE: usize> Io<'a> for &'a ExclusiveIoMem<'_, SIZE> { +impl<'a, const SIZE: usize> IoBase<'a> for &'a ExclusiveIoMem<'_, SIZE> { type Backend =3D MmioBackend; type Target =3D super::Region; =20 @@ -292,7 +292,7 @@ fn drop(&mut self) { } } =20 -impl<'a, const SIZE: usize> Io<'a> for &'a IoMem<'_, SIZE> { +impl<'a, const SIZE: usize> IoBase<'a> for &'a IoMem<'_, SIZE> { type Backend =3D MmioBackend; type Target =3D super::Region; =20 diff --git a/rust/kernel/pci/io.rs b/rust/kernel/pci/io.rs index 4be33ecb4192..4d1d0afdc491 100644 --- a/rust/kernel/pci/io.rs +++ b/rust/kernel/pci/io.rs @@ -8,8 +8,8 @@ device, devres::Devres, io::{ - Io, IoBackend, + IoBase, IoCapable, Mmio, MmioBackend, @@ -144,7 +144,7 @@ fn io_write(view: ConfigSpace<'_, $ty>, value: $ty) { impl_config_space_io_capable!(u16, pci_read_config_word, pci_write_config_= word); impl_config_space_io_capable!(u32, pci_read_config_dword, pci_write_config= _dword); =20 -impl<'a, T: ?Sized + KnownSize> Io<'a> for ConfigSpace<'a, T> { +impl<'a, T: ?Sized + KnownSize> IoBase<'a> for ConfigSpace<'a, T> { type Backend =3D ConfigSpaceBackend; type Target =3D T; =20 @@ -267,7 +267,7 @@ fn drop(&mut self) { } } =20 -impl<'a, const SIZE: usize> Io<'a> for &'a Bar<'_, SIZE> { +impl<'a, const SIZE: usize> IoBase<'a> for &'a Bar<'_, SIZE> { type Backend =3D MmioBackend; type Target =3D crate::io::Region; =20 --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from CWXP265CU010.outbound.protection.outlook.com (mail-ukwestazon11022126.outbound.protection.outlook.com [52.101.101.126]) (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 68B3747276A; Thu, 11 Jun 2026 16:28:40 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.101.126 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195324; cv=fail; b=rTAeYSWE9Ro/kLjVdLq3H8LtRuRtHxG8e+vAtyUMLDpydKTnwQhtsdj+Ng1QFDMCEhsnZu67FgL5oDNq+yuDFp6nXVuTb64NMeH6E9hfa6c+1fp/poJuOq6dLKDsGKjb2FYy1Jwil26fNaj037zYq0OW7Z3aFf9o7iG1B1kyXDU= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195324; c=relaxed/simple; bh=BMHlZuqeKIOpjPrmR887sn0p/bQpz2qvFneWEVNxlaw=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=Rcij/SLESIg5X2M/UmCh4alEdiPDBQPkG0iWBDQGLGfzZN9PSCUYDyqzySYhEVT9zCVqwRviuDGu+Zif9xxNcjT253jSBj30on9My0epyxf2McZ6hMUG1rcDtVvot7D6dpfiY0bB7UmU2nhwZ8W+aZsxShCBCVbG2jBy/ztoN4Y= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=GTqa9Eol; arc=fail smtp.client-ip=52.101.101.126 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="GTqa9Eol" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=GyVWMRqPuXH6dusikOBtsl/W/yA+xKooziVhcmBiFlToPvAXkp0hmsi60D3YaloZtCmKKglkBdMGXdNvXf9HLIyW+NDfBGwHus/lBI1ZVA3ctNob6hYb3LfVS6Qzbrty7UFdaalq7ksgEe1CdDuYz6YmI94bsfpz6aTm1xwgvTtHF62qsR6fXiPa4lErXGq8e0DPZGtCnIs4eeS/INs9plEXKwFEnlIqRpV03BgDyXaEetM948S5UxEw4IQ6mrrWUk0hyDWb6I3yDBF2P1CHCHysSDHoI2dR7QtY7rgwKKHgycjdG6FttCUd41xD43Pj3ZmADvf+6uqcosdgUb3+Sg== 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=yeG2do/HPdyDiGshtJW0A25oqZztHLd7ZA0ynJO+RcM=; b=ajF5CO4Y8im5YZInY0kDyyKaEBAZOVAOz5qvZo/ddpztWuEAsG6ScTjoYgn2EFzFxswTjldtXis4M4GMlov61HrLHslfldTdDuq1eH1klzr7ZgtW/7hO3MJDzaaiSnJidH43xbkg90LNepe2HVB361Bjb/Um1/bcebQn8U5+4Q3E8C7pSHU1a38wccMFo5Jw2zIM6kVh2OcgOG+vBLxm4kSBxUgU/awfUMvMXYRpHI3KQ21TWQtufjeL02wLuXwLd3eu3SdT10M9KTdVtW27/kmHO18cDHde9jfr6y4uSr9iYU0hlRhL9WnaVdf6im5oXJucAGGv10wnNmH4jKBfSQ== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=yeG2do/HPdyDiGshtJW0A25oqZztHLd7ZA0ynJO+RcM=; b=GTqa9EolGZmYjs5H0mn8xeHKRbc8LA2xrKrBaOii96ggNmxON/C3DSOCk71Ycc/JpvyPQ+cH1uDRzloOpbnmw643BgOlCkMlQrizn4Qu7/NKYC9fqSttD8UpxbbE9Nmg7LV8J9EJ4ZTsiLLqSOi1gIdgH58trtViYaPKauRyBCE= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO4P265MB6525.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:2e7::9) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.11; Thu, 11 Jun 2026 16:28:29 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:29 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:14 +0100 Subject: [PATCH v4 12/20] rust: prelude: add `zerocopy{,_derive}::IntoBytes` Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-12-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195301; l=1101; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=BMHlZuqeKIOpjPrmR887sn0p/bQpz2qvFneWEVNxlaw=; b=lCIwzNaVjx8MgBPV1IrNWjj9xccFQYcWNGRMCqNm4DRaWfnbbllB1X/ZqkxXDj3KEo9De0ubS 9XuW1zV5SfYAwuqMK4auTLMdh+kAm+jp6CNoWm1WL9A+zQJ05p1XrG5 X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO4P265MB6525:EE_ X-MS-Office365-Filtering-Correlation-Id: 8536713c-55e0-4d2a-8b15-08dec7d678ca X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|23010399003|376014|7416014|366016|1800799024|10070799003|921020|56012099006|22082099003|18002099003; X-Microsoft-Antispam-Message-Info: x7xVhm/pEhMTjjlA/5KJxWhCLJDNaFo6qJtlfaTgnGGUr7UBGJpSW2nV6AbyVzBzK7P9q9aCUYdOPf3ONf0Tpr6rHWQkOX/UVDeN61ELlnqkF5O+GGJZP0/tS3OOW27b3744hRWtaionnn/Z5H0gRMdvfyc/0p95C0QCXST0qC/TzcTyDAqJyKbP+Dz2QdapSP/2lCD+7khwkpMT6zVtDVlcoNnkGZ4y/Un8xHpLrdR9TM5TAoHbgCQdct0LQBb2BlS3xImNKwR7McfGipWBbjdsWR+O0hlBlgCGudeMCqUBC9nFzzRuW7Fl2kEcSIlsOzd2HTVScxojcgfo6lv0So07rIXSo+SwvEX0gf2PT7lz1i8JKEIPX4rD5oBfTX0WXBmgW/I624RqmQLNCEuAounWDIxL1IQWXhKqfyWwnTyj5BWsY7t47eBekoZG0vcun6FhXe/UX3/aYXjwon9kXkhERk5wHnuqOOSRysqvdNLRI/sDFLwIAJLgn2wrjJeA3+1keX7G26oy9oODaCjWGwc79dPi05ohLC6W93NeoiRYdiIhTwCwasYtiGdRIKHefFi6dbirrIMbp6gaI7WdsxgRSSmzymdkEZQWCIqFeIIz1aikf+DmhHbO9lifrY5MQwFyRCg90XIZQrm8TXLyoftML9WY/dLXbXxcUYI46lDSfT05Vz9HPc973SowHa3bY4pXEy1WddVlk29iDbsNERExCRb0ncdLnsJ6KX0DDFs= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(23010399003)(376014)(7416014)(366016)(1800799024)(10070799003)(921020)(56012099006)(22082099003)(18002099003);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?R05zSExqdktQaFJ1RTV6MWNZVEZMMElGY2xtNXY0SE9zdUdnSWs5NDVUWm9r?= =?utf-8?B?SlpkWlgvMTZCYldDNE1LRVpnL1c0Snd0Q2xVTTZ6OC9zd1RyUW1nUndqeHZo?= =?utf-8?B?UDFyakcxeHVOcHl5ZFN5NHpseVhrSHlBU3NJZUYrN1RJT2xQQ2N3VjdERmRm?= =?utf-8?B?cHRaMTJYR0EvRU54NWlwM2o0VEpzY3M1ZGhmdVg1YVhKRk9vQlhJdE5uRWlK?= =?utf-8?B?OTAya3pnMDJhL3VWb29ncUNMNUkyOWduWFlTWThvblB6Tk5UZ2pYcnoycTB4?= =?utf-8?B?MXg4RWZqS2xKVGtrcTFpTVRZZ3kxN2NtWnNRdHllNEtsNmxIR3RuR2FGU0JY?= =?utf-8?B?K2wydTZuM0JaaHJGK2d2STR0eFBXTEgwc3lzOEcwWUwweEJVNVk5cThiNDFx?= =?utf-8?B?YXhUb1o1YVcxU3VMRnl4Z2tzRi84OGVHakhMS2dUN0xzdkNVVHpqQm1uT1pE?= =?utf-8?B?dkluSlYyNEpabjcvNXVWdGVSM1BNSm5tcktBVEhMTzhaOE5vZ00yb3c2ZWUr?= =?utf-8?B?emdKUHljNk9LMCs2WklzbzZPT3Yyc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riginatorOrg: garyguo.net X-MS-Exchange-CrossTenant-Network-Message-Id: 8536713c-55e0-4d2a-8b15-08dec7d678ca X-MS-Exchange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:29.7467 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: DevV/J5/t9LJC+UjDW8VuCuHaTVvIavNpuq4ivnNk/1pyJ3kZT3x89+x6sFEa2uJ0LYIzGKSPr5zCc7i9PsOmg== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO4P265MB6525 In order to easily use `IntoBytes`, add it to the prelude. This adds both the trait (`zerocopy::IntoBytes`) as well as the derive macro (`zerocopy_derive::IntoBytes`). Signed-off-by: Gary Guo Suggested-by: Danilo Krummrich --- This is wanted because I want to convert the upcoming I/O projection series to use `zerocopy` traits rather than keep using transmute module. It is most helpful for derives in doc tests; I do not want to explicitly use `#[derive(zerocopy_derive::IntoBytes)]` in the doc tests. --- rust/kernel/prelude.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 8a6da92e8da6..ca396f1f78a6 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -61,10 +61,16 @@ }; =20 #[doc(no_inline)] -pub use zerocopy::FromBytes; +pub use zerocopy::{ + FromBytes, + IntoBytes, // +}; =20 #[doc(no_inline)] -pub use zerocopy_derive::FromBytes; +pub use zerocopy_derive::{ + FromBytes, + IntoBytes, // +}; =20 #[doc(no_inline)] pub use super::{ --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from CWXP265CU010.outbound.protection.outlook.com (mail-ukwestazon11022106.outbound.protection.outlook.com [52.101.101.106]) (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 4E718480946; Thu, 11 Jun 2026 16:28:43 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.101.106 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195325; cv=fail; b=Gpg4rJvAw5DGbxPjb3GDyVtAigzSY5H5Etuw56WssUA+f0uR29R5iPDSr8h4ChnhYToSty2IVpIuJUPDIz1NHboraI000mC2LSde91i+kZ3U6uVFGARHHSnY4xVLZy1B31uBCDbtawWMpjZa0VkmWVlokUWOiXydGlIWgOXZwCg= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195325; c=relaxed/simple; bh=0Ouuv4rEG6K7m1QcFobtEFBysyYvLBM3w06T/IkWO7k=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=X9oC6JLYWKbpu7YI5tNhqC2Yid1VYfa6XPAReaoz/26ofIWO5z5BwsrR2c/U1NQM90SjX2c/pmr/SebJH0B0oqtAm3y9iepwbPMMPExrM63MEmFOBWSD3YMrIIOYmEChf/tWFMD1blVmezPll0ykdLrc42DMOEyFpnKG7AKXemU= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=RfhFR61D; arc=fail smtp.client-ip=52.101.101.106 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="RfhFR61D" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=wmAz35V88emDkO3UaNmFVMe8/BdGMnGei8hR4bfAqmcYBxUZHEPPdIsCZydvEwmrVGsM09v1E6vBhNMgR4JwXDCEzeGBNYOM42eYxTQ0N1VgM8iF1Gn5hq084sisqsbmnkCdGYQ+ks/apNwlPf8+5eJ+CxheioC7D9fES1SokmuGQAfy9xRtobekMGpRBm1s8D+4nhxB8FQ7X2MOY4DG5bartghnqQC5WYNXjNMMNLDGUPY1XL3k7+Nas76w/Awm3YZ+aiad+J6nijx130LlaiTzwI9rqWjHq0ksPCUz0rBsn/v176nYlBbarW/c48tjBPjWFnbmMzJTmrS6INpBWg== 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=zKy/1dqDfkwi8oiOKg7Hf6ZEHqb7O3P6mPojB/g7VmM=; b=PoLFVQEks+qA/I9owVIRJR1eSdptkteMbJWjBzPvli9/jj6rXm9HdSbJKCt3TqD6F84+QuFhCpUZO28kU98yGoxr/rrQFjwuXovUQB/ktE9ej4+fVDt5QAIAUiBzyzprtlBMnl1o0e1Ee5r3rY7EZk7TdWTRz1JuobMJOTzwSAVmvxP7bfW+CwDETVY5ON8lNQBRFIe1G92vt/NdwI9/qyKHtwSSdF09G1KrVuq5sUkd+3EMDFc4hTrwzsE9Fb0CLI45qEhzyr97yAJIsS5xPvBFx4O7P58PBXhL2OdKB4O7+mcYrva+etIgLQhiu24oJadTIZb/Z15GBgNXUnI7sw== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=zKy/1dqDfkwi8oiOKg7Hf6ZEHqb7O3P6mPojB/g7VmM=; b=RfhFR61Dul6x+J3NfKEF410SMvb745P22X1onHf0HE5dqyu6XmfDxqX06+458F60ElkIWlz6swhYSdjQwEZF1BDbCdoHELEJ3RX2PBhL7T1fWg5AWI8EblsdEKhcwNW56X3tFZHk4Hyy2tgGCeP8jRl+U09UNVHhZqkNOEokTTc= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO4P265MB6525.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:2e7::9) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.11; Thu, 11 Jun 2026 16:28:30 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:30 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:15 +0100 Subject: [PATCH v4 13/20] rust: io: add projection macro and methods Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-13-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195301; l=5994; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=0Ouuv4rEG6K7m1QcFobtEFBysyYvLBM3w06T/IkWO7k=; b=FgmB+CU0jQnnM14thZ2DpsUaJQwsyvr8wZJ33J24qyM8wFpYbHFIFdQLXoHVXMyBPC0aRjAst mubNJsSodyHCNLaQ723MqYzic5ESCvgERCSwn2mlatzHjSyAKtyXBZm X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO4P265MB6525:EE_ X-MS-Office365-Filtering-Correlation-Id: 00b8405e-4230-418f-ea70-08dec7d67920 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|23010399003|376014|7416014|366016|1800799024|10070799003|921020|6133799003|56012099006|5023799004|22082099003|18002099003; X-Microsoft-Antispam-Message-Info: mG43alH1TIyEi0l5xKjNB7wGQAIyYW0xA4JP9OhXYkrBhy2qQYqTjIWRJBxyS4HAeMPgRWDPBU1TD47gfdJzpSPqJ3mzTrBr4DHlM9W/dTHyzjVYCc1kcKO1sQy/WLELDMrSTPam/1wZlxRQK0PVJmAyyKpLNrTBL3ktLRlHj3Mk3lZkFNQzQZF7Pyc29rbZ6gdVXbBabpLzTVMg9Q+pha6ygONlGwrTbedT78JeT/CMc749PCPJKePc/uZbUX3FROb3iCJ4ZQ78B+SF8D/XG1zZMAlSXwZRIXagQipCnWa1QDbzVFPWlFTg1NhPtCWL0MMiOD5L7+Laexg/63kY+5rfPgJ72YLMokIDgRdJEuy9h8yhHpMhR+gbAy9NzdTNLFRJPqv/Q3yg1W6bC7RJIOSxMnZTzuaxQ8r9fHorRv4Q/u4hEHSLIwKAdTiF0EI3KC4yR2/WDnjW6fSrG0pkjt+xBx/V1Lye+2XboZza1Bq1RApycYxFSfDI4hVVXfKKfh8/f8+XKX+KU+oo7cVDi7evpqkSwJG0/Jt76V1RizhjqJjz42HPK6R/6u0bLmOK7dTRBWSrRCN5pD968JQ7pgRbGY6qZfLeJCnVMYEi/xquUkSNS+a4oUhscbiKcLecpXir9AUXr7E1TC71QOIKda3lS1Bg6lmJJ8SqbV+xbB6yqEJZYcla51VElptxMRwD3M4ypQARf5lIu70G7014CQCMkQ3PkLgldEkHamk45Tw= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(23010399003)(376014)(7416014)(366016)(1800799024)(10070799003)(921020)(6133799003)(56012099006)(5023799004)(22082099003)(18002099003);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?b3NEMG9GU2twbTBFRG0rVXVVQXJpRWsrc3FqYTVXMU04cUwyWnRjRUE0SERE?= =?utf-8?B?KzlWSmhaTmRHZnNuanF4UGNOanJEb1M3dXJyKzVsQVRSeEI0dFZaZ3JRRlEz?= =?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cDhBWWFzeEpHU2Q2WjlCc1BDcmQ3Wm1wZHFo?= =?utf-8?B?QnBjRzhROGU2NUlNNE5GREE4NTA4OVJXcVBvaWhVMW1iTDcwOHpyNnpzc1h4?= =?utf-8?B?bGFXZ3U4SFc1d2tWa0pHVmtaRmRId25YSHkyUURsR1FaZ0FrKzRISVNZTkl1?= =?utf-8?B?MVUzZGswcmxIUHphaGNuejZkUHdNcjk5cjJqeC9TcGJUTDVJZVAxanp4THRF?= =?utf-8?B?MW9Ebk9PR0MxVjg3cDRIUTRqa1dnVHVOMlN1bjY5WHN4dVRVc3VMRUF6S2hT?= =?utf-8?B?SVhiYVowa2MrQWpsV0s0YWM4a05XeTd1QnRScmdVcEUvRVlsd21KUy9KbmJR?= =?utf-8?B?bmxEOFB1MktWRUQ2OE9pN0ZETWNyZlQwK3V5dGtqWnhma1RMaURSMWFlTmFv?= =?utf-8?B?b3VWOVFVNEg2RjQxRnI4djNmejJkMFhXNU1OM1pucHQ4enovZGIzZz09?= X-OriginatorOrg: garyguo.net X-MS-Exchange-CrossTenant-Network-Message-Id: 00b8405e-4230-418f-ea70-08dec7d67920 X-MS-Exchange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:30.3098 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: aOW9geFOm0t4uNQQp4O2BkXGXz5Ckg/1ZQU3SZx7V5OTONeCYcngQYta5YU1im4EDZR3MBWZeLMkbv9InQLv+A== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO4P265MB6525 Add an `io_project!()` macro allows projection from `Io` to a subview of it, using the pointer projection mechanism to perform compile-time checks. For cases where type-casting is required, the `try_cast()` function may be used where the size and alignment checks are performed at runtime. Signed-off-by: Gary Guo Suggested-by: Danilo Krummrich --- rust/kernel/io.rs | 130 ++++++++++++++++++++++++++++++++++++++++++++++++++= ++-- 1 file changed, 126 insertions(+), 4 deletions(-) diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index 470ee2ed9849..c7a9952af995 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -14,7 +14,7 @@ ptr::{ Alignment, KnownSize, // - }, // + }, }; =20 pub mod mem; @@ -44,12 +44,12 @@ /// This type can be used when an I/O region without known type informatio= n has a compile-time known /// minimum size (and a runtime known actual size). /// -/// This must be 4-byte aligned. -/// /// # Invariants /// -/// Size of the region is at least as large as the `SIZE` generic paramete= r. +/// - Size of the region is at least as large as the `SIZE` generic parame= ter. +/// - Size of the region is multiple of 4. #[repr(C, align(4))] +#[derive(FromBytes)] pub struct Region { inner: [u8], } @@ -91,6 +91,15 @@ fn size(p: *const Self) -> usize { } } =20 +// SAFETY: Values read from I/O are always treated as initialized. +// +// This cannot be derived as `derive(IntoBytes)` does not know that this t= ype is padding free (given +// `repr(align(4))`). +unsafe impl IntoBytes for Region { + #[inline] + fn only_derive_is_allowed_to_implement_this_trait() {} +} + /// Raw representation of an MMIO region. /// /// `MmioRaw` is equivalent to `T __iomem *` in C. @@ -295,6 +304,49 @@ fn size(self) -> usize { KnownSize::size(Self::Backend::as_ptr(self.as_view())) } =20 + /// Try to convert into a different typed I/O view. + /// + /// The target type must be of same or smaller size to current type, a= nd the current view must + /// be properly aligned for the target type. + /// + /// # Examples + /// + /// ```no_run + /// use kernel::io::{ + /// io_project, + /// Mmio, + /// Io, + /// Region, + /// }; + /// #[derive(FromBytes, IntoBytes)] + /// struct MyStruct { field: u32, } + /// + /// # fn test(mmio: &Mmio<'_, Region>) -> Result { + /// // let mmio: Mmio<'_, Region>; + /// let whole: Mmio<'_, MyStruct> =3D mmio.try_cast()?; + /// # Ok::<(), Error>(()) } + /// ``` + #[inline] + fn try_cast(self) -> Result<::View<'a, = U>> + where + Self::Target: FromBytes + IntoBytes, + U: FromBytes + IntoBytes, + { + let view =3D self.as_view(); + let ptr =3D Self::Backend::as_ptr(view); + + if size_of::() > KnownSize::size(ptr) { + return Err(EINVAL); + } + + if ptr.addr() % align_of::() !=3D 0 { + return Err(EINVAL); + } + + // SAFETY: We have checked bounds and alignment, so this is a vali= d projection. + Ok(unsafe { Self::Backend::project_view(view, ptr.cast()) }) + } + /// Returns a view for a given `offset`, performing compile-time bound= checks. // Always inline to optimize out error path of `build_assert`. #[inline(always)] @@ -988,3 +1040,73 @@ pub fn relaxed(self) -> RelaxedMmio<'a, T> { // MMIO regions on 64-bit systems also support 64-bit accesses. #[cfg(CONFIG_64BIT)] impl_mmio_io_capable!(RelaxedMmioBackend, u64, readq_relaxed, writeq_relax= ed); + +// This helper turns associated functions to methods so it can be invoked = in macro. +// Used by `io_project!()` only. +#[doc(hidden)] +#[derive(Clone, Copy)] +pub struct ProjectHelper(pub T); + +impl<'a, T> ProjectHelper +where + T: Io<'a, Backend: IoBackend =3D T>>, +{ + // These helper methods must not have symbols present in binary to avo= id confusion. + #[inline(always)] + pub fn as_ptr(self) -> *mut T::Target { + T::Backend::as_ptr(self.0) + } + + /// # Safety + /// + /// Same as `IoBackend::project_view` + #[inline(always)] + pub unsafe fn project_view( + self, + ptr: *mut U, + ) -> ::View<'a, U> { + // SAFETY: Per safety requirement. + unsafe { T::Backend::project_view::(self.0, ptr) } + } +} + +/// Project an I/O type to a subview of it. +/// +/// The syntax is of form `io_project!(io, proj)` where `io` is an express= ion to a type that +/// implements [`Io`] and `proj` is a [projection specification](kernel::p= tr::project!). +/// +/// In addition to projecting from [`Io`], you may also project from a [`V= iew`] of an [`Io`]. +/// +/// # Examples +/// +/// ``` +/// use kernel::io::{ +/// io_project, +/// Mmio, +/// }; +/// struct MyStruct { field: u32, } +/// +/// # fn test(mmio: Mmio<'_, [MyStruct]>) -> Result { +/// // let mmio: Mmio<[MyStruct]>; +/// let field: Mmio<'_, u32> =3D io_project!(mmio, [try: 1].field); +/// let whole: Mmio<'_, MyStruct> =3D io_project!(mmio, [try: 2]); +/// let nested: Mmio<'_, u32> =3D io_project!(whole, .field); +/// # Ok::<(), Error>(()) } +/// ``` +#[macro_export] +#[doc(hidden)] +macro_rules! io_project { + ($io:expr, $($proj:tt)*) =3D> {{ + #[allow(unused)] + use $crate::io::IoBase as _; + let view =3D $crate::io::ProjectHelper($io.as_view()); + let ptr =3D $crate::ptr::project!( + mut view.as_ptr(), $($proj)* + ); + #[allow(unused_unsafe)] + // SAFETY: `ptr` is a projection. + unsafe { view.project_view(ptr) } + }}; +} +#[doc(inline)] +pub use crate::io_project; --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from CWXP265CU010.outbound.protection.outlook.com (mail-ukwestazon11022126.outbound.protection.outlook.com [52.101.101.126]) (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 8BAA7481AB8; Thu, 11 Jun 2026 16:28:44 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.101.126 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195326; cv=fail; b=eDtSa7RIrCyQ9tom1FDNT+UpDZXomnVHAplBV0kZysqbOYqnX2vT76slah+bp21N4CGPN+tNHVztd6p2sWifn5gPQcGXDLlDPQwQ902xMEl/9vsuCuWwmhTtf4HTJUZdoO4C1WUVPy72BawOdjQ7CB+h+g566/xUzA970Myq0H4= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195326; c=relaxed/simple; bh=VgsN9Sg1dp0TUbG/ok+GvKH00Dv8r2Kv2dJgDG8m844=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=chU1HHfv8A9po0gpVo0fQ2/dU0NBNGxqfupbI+MCnQvLxo/4f7Rdv2MO0tYzMC0nXJLv8BOoFISjH8Lwe+lgL4nkMXrsVw3rBdaPoXBMz7TqMVn2sKgl20aTyGiL8qj60zXl67kpeDdNgOuD2z4x0gW2sKksDpHzii52pT4Yqdc= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=hJGTmUim; arc=fail smtp.client-ip=52.101.101.126 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="hJGTmUim" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=oB8KRwOLji4PFew2JUmRXK44joGr/GZbEVAmbx2ZdKCLnk0wbvciyaqPk9SrhRfyxrHIzlTpAIyr4fHscKA3sNrjez3Wg6ugUdP4EEtiqdsH0s95X0LzUqga4dpF36XyivvegX+07RnrsrrhLwCG6KzKIYiEGqaq/xIqdWqKKDgWZ2WY7HRGUuEMOnKG+IkK8q1K96UAVUSPEM1XCIkcFxhTns+03nDCRfDkLB839Gbhpp8z1GWXUbHS08KZYbGKCKaTm0PQJIywl64yR+DykQMvVwoltGROBJaWNvY5nz91lP3RTGRcyC6+drX2kHASDUWzU2adxgwOkq6ZZ0KksQ== 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=qN9tqfRafOv7/7gE0QTzPm6f7EJUZMUQgF6JoPKeX7w=; b=a5VwWTRigFSfg+jdx6GSsF8bi0Ls65l/tiYGxLX2uSlttG6NVgiUBWunnfcLNjSvV8HnUpGRDTR4gKcyxQXhzEXypdQAz8neSRsgTDlp7/FXw1kAykBe6pSM87YGakJ3Lkr8TfhckaYWvkVxskTUEft/N4iJf7i9fOiKZMi+o7jY1A7YbYw9/ELkSc8R0BC3GYtmfi7vFXylSLqLmOblrTO7Ztcfl+yQA00j/ycURhDyJHHwJrriiFl3FcYNXK1sBlAfTT/mFiVspP1WfYi8zACG+1vjUcaV6zUiWv3mtMVXmdgsFB/6yPaU0fZclCvXDV1sJRTY94RskGoGYcbOjQ== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=qN9tqfRafOv7/7gE0QTzPm6f7EJUZMUQgF6JoPKeX7w=; b=hJGTmUimJ7HZbTkISqDVPrlDIDCvyfy3eIwGOlHMw75qAuEHoUgPTOa8gkTGdcp1VbpCbs6jgohsmzu7ellTwQ46DnsM9U8SN9/bhgCFL++KSI+tXF0reY0FdvwrokQhwP2ufoJbLvZ/ZfurjmvnuuiIs7U+ngFr80+UhmKegFE= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO4P265MB6525.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:2e7::9) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.11; Thu, 11 Jun 2026 16:28:30 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:30 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:16 +0100 Subject: [PATCH v4 14/20] rust: io: add I/O backend for system memory with volatile access Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-14-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, Laura Nao X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195301; l=5302; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=+3g3zjrIMkWzE2l+dGN2VRMKCNbJcRYKIfHVvT2+YxM=; b=Ffyee4+SHyduFhIbRrhbEIC1vI2mUlEsOQB+SvqbwB+wLJX5qMfE/OZV4Gv3En9kDfb8EKI3w PS3UttHm9f+AQlcV29eWpOCbZ7sLcP4x2D2dzzZcUifwLjHh5C0oLvl X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO4P265MB6525:EE_ X-MS-Office365-Filtering-Correlation-Id: 6ef24a40-c177-4746-28a4-08dec7d67977 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|23010399003|376014|7416014|366016|1800799024|10070799003|921020|6133799003|56012099006|5023799004|22082099003|18002099003; X-Microsoft-Antispam-Message-Info: D5FGaUhJ4nt0wUOc9E8zmWbH8dJQ0s3gv+xRUBFk6X72g9dW9WXrLWrj5yskvkRG+RRd2Ty7m9+htNrZMYqE1vMmWIk81/FJEY89zdmKNz3dPn+ev5v64iSPGc94cQBDcixpGUhsy33I4z4IcIxCl3InF0oeO+EXmSCjl2wiEjfNtU1shXdIoa3hD3AjqCwtXNqXuWho2N+HLWXWfnYqtW8YHGbo7kzNHPXgSFoyTWCOziI6V5xki4IPavyjCrDzmZA030m0dQ3JfjuBYwl7HUU2a/Tdcdrn2Gkv4gyRne+Q8vtdMwzAXwVbF++x1VdJ8hzTpcG1hW98fcZq+stUntOwEc05qbxmfhOmVLorX0IzC6IxtFe2UmuNYr8lpMMOeQvkD7JWfOND3T7QPgtrTqm+51+TkM5VOvgJzeGPdUaMrqA035cTVl0TZG8JzkNcTp4uVSFDbJiNIsTShIq1QqIcpkaoxumgKa+nXLsdy8oYcQKcHhxBgxVF0LOCsKXaBAuHuZLQmGmtc+flEOCNSwWkqXUfU1fV1IrmUgAKnslHCvk/b99hT0bS0ySnNFNSgytVJ1P5jBQageyl18nwFdvOWXoOqAHLaBmm8+iZN8MPsGIpgj62J2FDbS4ILaAn4XDw3LLAZUzDoUdRJqspPB8HQDrLk62xZKbRuBR0oKOEKkbcbbQyLUBqTkz2laxPSPR6GDaiSpRqG1WBaCq015z7phyWGHzUSF0EWpeYkQY= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(23010399003)(376014)(7416014)(366016)(1800799024)(10070799003)(921020)(6133799003)(56012099006)(5023799004)(22082099003)(18002099003);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?TS91Z210TEg4Qjh0bFJwU09ETlkwWHFUUjlzZ3oyZ0NDb0E5cEQ3UEFLTXYw?= =?utf-8?B?QWNJbnRKUWlvRDhGeCtraG4zYXRBODhBellvdy9RZFAwT1Y0MElXQ1VaZVJI?= =?utf-8?B?Um85NUhaSjIwb2ttSHh5aXA0SmtNcjBtVE04MFhXaklhVXFuTXZia2I1MVZl?= =?utf-8?B?bEltcW5CdHhyaHhmS3JPck91V1FNdEUxY1RNUHh6Z3BSaHYzZHpzSmlXV3RE?= =?utf-8?B?dXNlMmNCbjBvcjNDYXlKVlhUVytxbmtxbnp0NVh3YlBCdG90Tld3cGw1enF2?= =?utf-8?B?UGRZUitXTVB1UDJ4UTIrTngycCtDQTJ1dnhuN1pmdkF2TTZUb0pETXRsSzlG?= =?utf-8?B?TnkyVDFiTXFqeEY0TFl0UGdlamJlMzdsQ0Ewcm9xVHlQWHQ0N20yeHB5TTJu?= =?utf-8?B?VDNKNEpSL2pzYUMzN0dnWnpMMEovN0dWcHhlemJNVjhtcWJmbGl4MnRqT2Jm?= =?utf-8?B?UHU3VlRxQ2pTQXZ0UEhDUXozR3VOUnJRSTZrNFI5RXBYajcva2M1MEJ6OXR1?= =?utf-8?B?WVRDdlM1NkY5Z2p1Rjk1SEgyVExPdStjd1RBb2oxSVBiem9QTGFycW8wdlBG?= =?utf-8?B?Q05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177-4746-28a4-08dec7d67977 X-MS-Exchange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:30.8849 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: sijuWXL6nuk+nDwGg/udAM8aLXvx/O2hFmAfDbRgTOXPESe2BXUPifGQrZiSXE1xbkhJq4VAdj3XuZSkEoIKWg== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO4P265MB6525 From: Laura Nao Add `SysMem`, an `Io` trait implementation for kernel virtual address ranges. It uses volatile accessors to provide safe access to shared memory that may be concurrently accessed by external hardware. Implement `IoCapable` for `u8`, `u16`, `u32`, and `u64` (for 64-bit system). This can be used for instead of `Coherent` for cases where a different layer takes care of mapping the system memory to the device (e.g. dma-buf or GPUVM). Signed-off-by: Laura Nao [ Rebased and adapted on top of I/O rework. - Gary ] Co-developed-by: Gary Guo Signed-off-by: Gary Guo Suggested-by: Danilo Krummrich --- rust/kernel/io.rs | 122 ++++++++++++++++++++++++++++++++++++++++++++++++++= ++++ 1 file changed, 122 insertions(+) diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index c7a9952af995..a418c8cbb031 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -1041,6 +1041,128 @@ pub fn relaxed(self) -> RelaxedMmio<'a, T> { #[cfg(CONFIG_64BIT)] impl_mmio_io_capable!(RelaxedMmioBackend, u64, readq_relaxed, writeq_relax= ed); =20 +/// I/O Backend for system memory. +pub struct SysMemBackend; + +impl IoBackend for SysMemBackend { + type View<'a, T: ?Sized + KnownSize> =3D SysMem<'a, T>; + + #[inline] + fn as_ptr<'a, T: ?Sized + KnownSize>(view: Self::View<'a, T>) -> *mut = T { + view.ptr + } + + #[inline] + unsafe fn project_view<'a, T: ?Sized + KnownSize, U: ?Sized + KnownSiz= e>( + _view: Self::View<'a, T>, + ptr: *mut U, + ) -> Self::View<'a, U> { + // INVARIANT: Per safety requirement, `ptr` is projection from `vi= ew`, so it is also a valid + // kernel accessible memory region. + SysMem { + ptr, + phantom: PhantomData, + } + } +} + +/// Implements [`IoCapable`] on `SysMemBackend` for `$ty` using `read_vola= tile` and +/// `write_volatile`. +macro_rules! impl_sysmem_io_capable { + ($ty:ty) =3D> { + impl IoCapable<$ty> for SysMemBackend { + #[inline] + fn io_read(view: SysMem<'_, $ty>) -> $ty { + // SAFETY: + // - Per type invariant, `ptr` is valid and aligned. + // - Using read_volatile() here so that race with hardware= is well-defined. + // - Using read_volatile() here is not sound if it races w= ith other CPU per Rust + // rules, but this is allowed per LKMM. + // - The macro is only used on primitives so all bit patte= rns are valid. + unsafe { view.ptr.read_volatile() } + } + + #[inline] + fn io_write(view: SysMem<'_, $ty>, value: $ty) { + // SAFETY: + // - Per type invariant, `ptr` is valid and aligned. + // - Using write_volatile() here so that race with hardwar= e is well-defined. + // - Using write_volatile() here is not sound if it races = with other CPU per Rust + // rules, but this is allowed per LKMM. + unsafe { view.ptr.write_volatile(value) } + } + } + }; +} + +impl_sysmem_io_capable!(u8); +impl_sysmem_io_capable!(u16); +impl_sysmem_io_capable!(u32); +#[cfg(CONFIG_64BIT)] +impl_sysmem_io_capable!(u64); + +/// System memory region. +/// +/// Provides `Io` trait implementation for kernel virtual address ranges, +/// using volatile read/write to safely access shared memory that may be +/// concurrently accessed by external hardware. +/// +/// # Invariants +/// +/// `self.ptr.addr() .. self.ptr.addr() + KnownSize::size(self.ptr)` is va= lid and aligned kernel +/// accessible memory region for the lifetime `'a`. +pub struct SysMem<'a, T: ?Sized> { + ptr: *mut T, + phantom: PhantomData<&'a ()>, +} + +impl Copy for SysMem<'_, T> {} +impl Clone for SysMem<'_, T> { + #[inline] + fn clone(&self) -> Self { + *self + } +} + +// SAFETY: `SysMem<'_, T>` is conceptually `&T` but in I/O memory. +unsafe impl Send for SysMem<'_, T> {} + +// SAFETY: `SysMem<'_, T>` is conceptually `&T` but in I/O memory. +unsafe impl Sync for SysMem<'_, T> {} + +impl<'a, T: ?Sized> SysMem<'a, T> { + /// Create a `SysMem` from a raw pointer. + /// + /// # Safety + /// + /// `ptr.addr() .. ptr.addr() + KnownSize::size(ptr)` must be valid an= d aligned kernel + /// accessible memory region for the lifetime `'a`. + #[inline] + pub unsafe fn new(ptr: *mut T) -> Self { + // INVARIANT: Per safety requirement. + Self { + ptr, + phantom: PhantomData, + } + } + + /// Obtain the raw pointer to the memory. + #[inline] + pub fn as_ptr(self) -> *mut T { + self.ptr + } +} + +impl<'a, T: ?Sized + KnownSize> IoBase<'a> for SysMem<'a, T> { + type Backend =3D SysMemBackend; + type Target =3D T; + + #[inline] + fn as_view(self) -> ::View<'a, Self::Targe= t> { + self + } +} + // This helper turns associated functions to methods so it can be invoked = in macro. // Used by `io_project!()` only. #[doc(hidden)] --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from CWXP265CU010.outbound.protection.outlook.com (mail-ukwestazon11022106.outbound.protection.outlook.com [52.101.101.106]) (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 F046C49218E; Thu, 11 Jun 2026 16:28:45 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.101.106 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195328; cv=fail; b=OAB+kWNYiv8hgQup3xIQP5Tw5f0PWNCKPX3TwSKGH5VAd1inq3WD3CbpsY55SIBWccJwiNG9bj+nEcwI0IWbcEJx92/iNk1fvIDKaV/BINHvYMNLCipSDLrFGRdEpBuu7oLGzKdMYRj7Kie0dWf4NKtkrTBAC0bEoMhnGcaTtbE= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195328; c=relaxed/simple; bh=1KDVAjQDV95PM3cfyWvcXgbs2vPjx8HAx1il87YdtO4=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=G25DFRJcNLpoAG3zyNDcnuTcrdRhRxDvlhlLQqMwTLxTmjNzGOO+61sv6B906YBNJuR1TWY/o0CbE6J6LlS2rNw24PSqj5Bj8QScEqufVkd+8sJIDFPyP49tixx5Smh+FyqXDKwKqjrPIhZw67KUJElTk4JEobh54DYIPkVCp2I= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=hPCnsMEc; arc=fail smtp.client-ip=52.101.101.106 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="hPCnsMEc" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=PQXGePBBfXa+yumTqNfQov25nx098EE4nZFQqh7TSzgqn3FPfPf7D8GiiE501M68O4qt3e34PsSfqW93XOgSvibXx4vT6qRl8FdXPvIe6MNTvcwes7DjIaknwRif6RFT+fOOGaSfnABdAEZE3dKwmeihlsUMy8ry8UYnVaMlxsiNuz8mHyW57RPE2sv1YQDE2bVQYYyQ7+qzXS/oArH2AtJhBlAoiqJib+ovQOvueeQeQWALzfjy9dv4/z8A31ryVpAvBJVhhL/Vi8NiBL/qNb7Lqzj2iQ7kpCnT9szlmBKzT1QkJwyMlV0SGZzZzZrhZujcKvdZF8coUX62czfh4A== 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=cFdRUcJQKUmV8oOcbV0z2r4i9Jy5D1L9pgQmGTpA1mo=; b=ROp3AH+VGsAzEFU8H1mOyi1PEYr98GFlNObEmP2xcfZ6hdV1UY4J0sEnyKph66nGqrRltfR5LcJMUww5qRrBHnGVA7U1pXDC8rldr4IxYzaRMIyfiZVITIl8QOTMEoUEo+qtM2/ujpYE5qtDyNxljo3YrPxNXqy854uHF9Dz6toXAtiuv1kETKObBUoP0l9Na9JwVQ07F+hcnJSqRRzOl14Oczo9LPgEaejGJq+3fJyKnrCt5BtYGCbODxBqxcluZE0rP1/TOtQl1yo/Gz+/nDOmH17PvPjb0TstOPaCpgk4tnBeMvdImmol4LfmqeWTLlqv1IeBU/+LS/deX/tCGg== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=cFdRUcJQKUmV8oOcbV0z2r4i9Jy5D1L9pgQmGTpA1mo=; b=hPCnsMEc4L2ZbDx/hjj1ZP3mELzbhrzk+9ZXNCA5CmK9LvgyP8wojTVEsySeXqQUVcfY6MpwQ7DeReZjXdpdVVinW8eqJHYJgdRoNLTSNZra4iKF/LMzHHuqOwzoOiuhJX+aO9dcH+T43ae8ZmUP7BiTPCebd77zF7bdFGTfr6o= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO4P265MB6525.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:2e7::9) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.11; Thu, 11 Jun 2026 16:28:31 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:31 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:17 +0100 Subject: [PATCH v4 15/20] rust: io: implement a view type for `Coherent` Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-15-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195301; l=5630; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=1KDVAjQDV95PM3cfyWvcXgbs2vPjx8HAx1il87YdtO4=; b=c7xzNkTsWyiJmKWVAGEQpL81CRSxBBYivP+ay1LdYHixnomtGZ7XpNC7okK+pMDRBhcMGkRsS XsUdtaluzWsCNTURToWIKpyVkF10g3LeaP8hMTMlDZiLu5vSBfOxa/u X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO4P265MB6525:EE_ X-MS-Office365-Filtering-Correlation-Id: e64add29-28fe-4cb2-8fd6-08dec7d679ce X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|23010399003|376014|7416014|366016|1800799024|10070799003|921020|6133799003|56012099006|5023799004|22082099003|18002099003; X-Microsoft-Antispam-Message-Info: pyXQ3WVdA/x4Yhs8Z8GWc9QwsKf56h+4jTLtdiHvlYspdcgyN9fVrD9NafZ2ieebWEDyMAjmfRrxHxATKM1tNBGnBR9tMWY9RXhlcj5iq+yAsHzjhUJCs6uavzhAXeEZ+29XuyqyQeQ1OqHBPFaPWF6ZHQpZbfWJ1rTEo5qJseeTD6ttVaGWWSffGvUdH2qv+mwqKpRbWiCq7l2XqWgbK4bk9Jat8Aw44/AFuWCeJIXUKAuB8OBCf4wF4ZC4wZmACccECkkUGz1oX4mE94Q8SFbhpY+7aqGVKgc97/qpcJXe6+NZob8asX4gBpVRdj8YuMvxljEdw61p+P1a5t9d4owo+cMfe7IbVGQIvaf+t/QV+nzbTWNS8fWHd5EdGw7oSonUec9EDewjDlHye6h/XQqzB4mCVJ55VTUBIA5ubk14Hz99k9kasu/nzE0JeWs5LX4yUnm4ydOBGdmoQ4KNlmU+4gp4fdAJG9tThjX3rFjfhwEejdJMeL8n1z4Bva0hsazfK/44CuR9YKzaPnNc0zQ36RGbSKWRTDPLDkTiaZ+3gkWTJX29vleMqCklAidVy2nLfhSgJDONTIaLrBXsI4LEAu3FRYqrI7v7aqyb+QYeUdeG8RSKpOzu84+IEeOMSQhqQ7cfj3CEEszlEMs4L/tPI2qIYgf6E6qXFRmSKHLIDmBIvIbbUI62QWPg1HFt50MNsgSRaZL0VZ1lIUTmVegKaCz2qD8uStPWM5ygIoo= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(23010399003)(376014)(7416014)(366016)(1800799024)(10070799003)(921020)(6133799003)(56012099006)(5023799004)(22082099003)(18002099003);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?SmV4N2ZBQWNpODBYZ1hYSDdTck5NNmlyV253d2VvNndCUW92L1h5d3lnY2Rz?= =?utf-8?B?M0ZIcWduYm5hNVJoOURzdnR2d2ZqRHNLR0J6WTFHZk01dnRyc3hnYm1xSXVF?= =?utf-8?B?byt6U2MybVdGVm45QWNFb1A1blJnbnVVRmtlZXNBc2txeExXR3h2YXZjeW10?= =?utf-8?B?cUlzTXlNVGxTM0NDcTZnUklVc0haNkZPbFg3VzlQcUk4ZVZDWWE0bWRzbW1m?= =?utf-8?B?cFJ2bnZhUE4vRklveVUxM2txaU5LczZMWU1wRVE0OEVOUlU5MWhBMkJJM01O?= =?utf-8?B?NWxqWjJMV2tYdG1Wc1JITmcxc29hcCttU1l5MmYrOTRYNVRoQmFINGpZQVZN?= =?utf-8?B?NVpzWUprdG9DZzhZNVQwWTlPZEtOeVlzY2RzRjd0Y3d4ZkQrQ0oyM00zZU96?= =?utf-8?B?ZVdIY3lyaUM1T2V6SFNscDEwVmdqOTMrVURvQUFaRT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k1VGxvUFh2M3FIR2dibVRITWJ4dTA2dmRVLzAzT1VS?= =?utf-8?B?OFRUbUZyZ3k5bEtqRU1oVTVWZFlpMnZ2QTI0RE9ycnZyaTBrSGNjQT09?= X-OriginatorOrg: garyguo.net X-MS-Exchange-CrossTenant-Network-Message-Id: e64add29-28fe-4cb2-8fd6-08dec7d679ce X-MS-Exchange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:31.4660 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: s1OMj9mXTc2cIjQVL4NX4ECfaFM6Y/OcZiZRMmHpMQeku5S2Kc1n5EEh7x7AGtGzvdMLSaJaEAsbZ0hTXPz0vQ== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO4P265MB6525 Implement a `CoherentView` type which is a view of `Coherent`. To be able to give out DMA handles, the view type contains both CPU and DMA pointers, and the projection method projects both at once. Delegate most of the `Io` implementation to `SysMemBackend`. Provide a method to erase the DMA handle and give out a `SysMem` view, if the user does not need the `dma_handle`. Signed-off-by: Gary Guo Suggested-by: Danilo Krummrich --- rust/kernel/dma.rs | 137 +++++++++++++++++++++++++++++++++++++++++++++++++= +++- 1 file changed, 135 insertions(+), 2 deletions(-) diff --git a/rust/kernel/dma.rs b/rust/kernel/dma.rs index 200def84fb69..ab6504910e4f 100644 --- a/rust/kernel/dma.rs +++ b/rust/kernel/dma.rs @@ -14,14 +14,21 @@ }, error::to_result, fs::file, + io::{ + IoBackend, + IoBase, + IoCapable, + SysMem, + SysMemBackend, // + }, prelude::*, ptr::KnownSize, sync::aref::ARef, transmute::{ AsBytes, FromBytes, // - }, // - uaccess::UserSliceWriter, + }, + uaccess::UserSliceWriter, // }; use core::{ ops::{ @@ -1133,6 +1140,132 @@ unsafe impl Send for CoherentHandle {} // plain `Copy` values. unsafe impl Sync for CoherentHandle {} =20 +/// View type for `Coherent`. +/// +/// This is same as [`SysMem`] but with additional information that allows= handing out a DMA handle. +pub struct CoherentView<'a, T: ?Sized> { + cpu_addr: SysMem<'a, T>, + dma_handle: DmaAddress, +} + +impl Copy for CoherentView<'_, T> {} +impl Clone for CoherentView<'_, T> { + #[inline] + fn clone(&self) -> Self { + *self + } +} + +impl<'a, T: ?Sized> CoherentView<'a, T> { + /// Erase the DMA handle information and obtain a [`SysMem`] view of t= he same memory region. + #[inline] + pub fn as_sys_mem(self) -> SysMem<'a, T> { + self.cpu_addr + } + + /// Returns a DMA handle which may be given to the device as the DMA a= ddress base of the region. + #[inline] + pub fn dma_handle(self) -> DmaAddress { + self.dma_handle + } + + /// Returns a reference to the data in the region. + /// + /// # Safety + /// + /// * Callers must ensure that the device does not read/write to/from = memory while the returned + /// reference is live. + /// * Callers must ensure that this call does not race with a write to= the same region while + /// the returned reference is live. + #[inline] + pub unsafe fn as_ref(self) -> &'a T { + // SAFETY: pointer is aligned and valid per type invariant. Aliasi= ng rule is satisfied per + // safety requirement. + unsafe { &*self.cpu_addr.as_ptr() } + } + + /// Returns a mutable reference to the data in the region. + /// + /// # Safety + /// + /// * Callers must ensure that the device does not read/write to/from = memory while the returned + /// reference is live. + /// * Callers must ensure that this call does not race with a read or = write to the same region + /// while the returned reference is live. + #[inline] + pub unsafe fn as_mut(self) -> &'a mut T { + // SAFETY: pointer is aligned and valid per type invariant. Aliasi= ng rule is satisfied per + // safety requirement. + unsafe { &mut *self.cpu_addr.as_ptr() } + } +} + +/// `IoBackend` implementation for `Coherent`. +pub struct CoherentBackend; + +impl IoBackend for CoherentBackend { + type View<'a, T: ?Sized + KnownSize> =3D CoherentView<'a, T>; + + #[inline] + fn as_ptr<'a, T: ?Sized + KnownSize>(view: Self::View<'a, T>) -> *mut = T { + SysMemBackend::as_ptr(view.cpu_addr) + } + + #[inline] + unsafe fn project_view<'a, T: ?Sized + KnownSize, U: ?Sized + KnownSiz= e>( + view: Self::View<'a, T>, + ptr: *mut U, + ) -> Self::View<'a, U> { + let offset =3D ptr.addr() - view.cpu_addr.as_ptr().addr(); + // CAST: The offset DMA address can never overflow. + let dma_handle =3D view.dma_handle + offset as DmaAddress; + CoherentView { + dma_handle, + // SAFETY: Per safety requirement. + cpu_addr: unsafe { SysMemBackend::project_view(view.cpu_addr, = ptr) }, + } + } +} + +impl IoCapable for CoherentBackend +where + SysMemBackend: IoCapable, +{ + #[inline] + fn io_read<'a>(view: Self::View<'a, T>) -> T { + SysMemBackend::io_read(view.cpu_addr) + } + + #[inline] + fn io_write<'a>(view: Self::View<'a, T>, value: T) { + SysMemBackend::io_write(view.cpu_addr, value) + } +} + +impl<'a, T: ?Sized + KnownSize> IoBase<'a> for CoherentView<'a, T> { + type Backend =3D CoherentBackend; + type Target =3D T; + + #[inline] + fn as_view(self) -> CoherentView<'a, Self::Target> { + self + } +} + +impl<'a, T: ?Sized + KnownSize> IoBase<'a> for &'a Coherent { + type Backend =3D CoherentBackend; + type Target =3D T; + + #[inline] + fn as_view(self) -> CoherentView<'a, Self::Target> { + CoherentView { + // SAFETY: `cpu_addr` is valid and aligned kernel accessible m= emory. + cpu_addr: unsafe { SysMem::new(self.cpu_addr.as_ptr()) }, + dma_handle: self.dma_handle, + } + } +} + /// Reads a field of an item from an allocated region of structs. /// /// The syntax is of the form `kernel::dma_read!(dma, proj)` where `dma` i= s an expression evaluating --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from CWXP265CU010.outbound.protection.outlook.com (mail-ukwestazon11022126.outbound.protection.outlook.com [52.101.101.126]) (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 16965495537; Thu, 11 Jun 2026 16:28:47 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.101.126 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195329; cv=fail; b=mQ4jJ0eWydPm3xqdUjIucbOczKGMfRh8r+j/Xxa4fEh4BIL1crdSg5GWpNUsK8iaaOo0/oIC0C2Z80ICiuTyXdYDv9vtyAAwWIhzlCoFeLNNMfsd0gTSrlVh0aE63ra0BhUjG2LSBf2cJU8oGeloWXhoXfeSM5Z9OncvVQrZjRU= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195329; c=relaxed/simple; bh=nZ1d5/awpoVPbX/s+fSI4bB3Kv514L1v9RLCo7wUgGQ=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=L8UTtaOgxHZVEK/DVU1fAor9Lq2M1beA+RMGkEg4nqnYczCqZcl2z0VSBbx+U+hocwku9040MgXV7nSBDM/sEVxVK/U4SnMNwy4dBMZzKTSEgBNqQoYBg6qEGef7hgZpkqMqiBODYnZMutfUJHo+plGpaL/8l7dBFZR1VjqC7No= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=L/77gcgQ; arc=fail smtp.client-ip=52.101.101.126 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="L/77gcgQ" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=kUg+4fe3j6eR9BZqqxYhc7BORdKZeQKc2Cok8GQ5qSBcoK4dMxIQOfRk7XDFReNz1CftYxbZLCtueu0AyZ2rSp6NA0oj3Kn+e4ai1pUVL39YyjbF0uo2ShrgXbzB2lPc8yAHjOayeynKhlbhq9zSm2IRJARupy0EZaZzvG7ywAa/IykbPf2vvXLvXdOFFr6AzP68Bra+9kS2fg+hOV9H1tKirq2h4bUOFLKI3Pu59y1el+/OM+Z5xP3ujd07ldl1VRNPCSSoHGuhsjJGq/M1IN+HBl5GwRsELAW6Pvz8wgTQJ6E7H5hN1O4Mc9sG/Me8UlHt1jHYvVywH1srSQxzCg== 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=nTtGLMvpsCIumS1SMAGZMboeYFmWAvp8G6alrtBQs54=; b=wCFQ4pJFBTqjsVIXQyonFPRmd2plCM0cA0x04RauF56kJn/oDGJUaCHx1V20BYDZbBnPpFSBRyHGm5LTZJEkvxd1d2KOSfOrRzttEHoXpxNDkUFLUmnw8ad1RncFmPAFLWocRxousrduGL93Gtjb8Un23STEcnnlbXPmubGi4e9fTE4xbttr0D31EvtJrocH+0JKyyNei4EQeQviCh1hB6T29kD5KDXE3W3DzcGItuJHYF3Tr1m0GTjXHTJF0EPKzyDWl6Ut72xnpIPPRRrNkYafz9YLL+TAwA0KA+1HlrUck753Mz2c9BVHxGAO5RTLh02boUN5LHWOc1VQeqLs7w== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=nTtGLMvpsCIumS1SMAGZMboeYFmWAvp8G6alrtBQs54=; b=L/77gcgQwfoeBvLac0EX6XW5lkORBkAQpu0PM8cC+anhH0G92rVkLGBKTdJuLk6yot3guKki7PNfnDis5e0W0lVx7Wa2XvaUvR5jeFYe5x1VrrsKLYOloJZSm+Czk2oMOS+fBZjQ7uYpOMqDXhKBwaFBImmjx19rjEYMQ7MaMmo= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO4P265MB6525.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:2e7::9) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.11; Thu, 11 Jun 2026 16:28:32 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:32 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:18 +0100 Subject: [PATCH v4 16/20] rust: io: add `read_val` and `write_val` functions on `Io` Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-16-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195301; l=4995; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=nZ1d5/awpoVPbX/s+fSI4bB3Kv514L1v9RLCo7wUgGQ=; b=Kr0ClBwFPyf7DXlVidnEzCEo7j4ylgggw49TwcWtOGvsj/aftM0jHIN6rRjIuvedNcgfiPCrX ikAobUMC84KC10pjpP+br/3eFAw6pQBzXxsbXaDs9lnITnJrxSDNxpx X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO4P265MB6525:EE_ X-MS-Office365-Filtering-Correlation-Id: 8b5072cf-b966-4876-16c5-08dec7d67a29 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|23010399003|376014|7416014|366016|1800799024|10070799003|921020|56012099006|3023799007|5023799004|22082099003|18002099003; X-Microsoft-Antispam-Message-Info: lyQLSUkORkeZkmHzpij6RnAgkTM5oMXSWA7gJmY5NtLpCONyIzA8qhM662+qdHG706tk87fr9UgszvsZ9XsVstkC9inPxqInN93pmXsgIUbZNHKDGB0c/D+QIz48bjUVT6WM+ogFf2h16aLYu62zGjuYHslrjI+aOOR02tZUDBJIMuuLJKPpYX/N4F1KpyWv0LjDgCzFaIR64x4kr+GsENUWOYJyFp1flycf+jbTV6hrdtThzeGNmY8DHIgw6kdx7K1acesUY+H4vpuuJqg47jhYybdkl/2et+ZFyqdMYOJMKf0UmYJKMQooBB/u3E6fq6w3PJLfkUlLapt2T3PMqXuTcauj9QdN4fx+j+0ev8sGSnu5VaAe+EjgXH+37VXRybC6HglI0WXmjpFtmdjWL+jap+ZpM0iLonffe1IdDANy//JDTfsTeEEYS0vcW7G8K68Wma47PGjntEr9eSoTmPu5eIVHGrC4OBylokcyaxtgsrF9TiTewuvt6eogEpytHuxLPNAqOss6xoN2jluJtot6ktGfSXBgtSfYC6ciLYXx/SymfOKWnwHvUbqpgBnq4NAp4Pbi1J9gRP4zzMzya67RoCv9U3TmpDlTfCW4lZOZz2DpJAEJOPiNtzZHbz02sZqVy4fy1LVkrraQw8s2UMC6pbSBr4R3UmNphmvZghWATlQlGlxrWfHLN4uPPh4+YPC5ZS4ZreHCpOcsPoKzn3v4UkNNTUhadBEz2oPgPhs= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(23010399003)(376014)(7416014)(366016)(1800799024)(10070799003)(921020)(56012099006)(3023799007)(5023799004)(22082099003)(18002099003);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?WDJtOGppQUVYVk84bDNjM2NUTktWL3c3K3VIdllvZGM2STdvWlJTN0p0Smov?= =?utf-8?B?bWtkTWRDam8zMVVYNWVRQWo5WGpvdFVPWmZPNzhYbUJRUDdyU0I3dmlMdDBy?= =?utf-8?B?NzhjdkhvNGwrRkltb3BTM2hkK3R2Q0RiQTlFMXNrMXFOeGhwMGVpV2FxSW51?= =?utf-8?B?SmtPNVIrd2dnSGx5N09uYjAvUzBjclZRT0xhQXZlamN2MFZheUxPSjdXZTlH?= =?utf-8?B?Q0Rm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NTh1eDlrYmZPWUZLQWZy?= =?utf-8?B?a3A0aFBycVVabUhOczVuVW50RE95QjVZWGVRWmZFblArejRvRDVDZWJHWC9V?= =?utf-8?B?MXV6aFd3Zk13ZGtYcmV0eGdrQjZ5OXZQOW84S0FIQlBEbXV0TjRlcmlGWTBs?= =?utf-8?B?a2lrd2YxYy9nbUxQbkxRVzl2Ky9tMGlCTkNSdldITWJmVlRmVmtwRXg0aWJp?= =?utf-8?B?ZWpjRythd3cra0Fxamd4bWdzTUpsMk16TUFLTm9ZUnpDNzJ5TUFqMHE5QzhB?= =?utf-8?B?cUppR3FJRUdCbktSR0JMclJnbmVrNlhBaWUxM3pEblFKWXJkWTRPdz09?= X-OriginatorOrg: garyguo.net X-MS-Exchange-CrossTenant-Network-Message-Id: 8b5072cf-b966-4876-16c5-08dec7d67a29 X-MS-Exchange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:32.0597 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: FyhjiX+bnVuqQFyHcxEBpPj2OQuxZB9djiAJleF6C0+v+xe6NhUx8i5Wod2irxBRPMrNZdHF39UOpMXVPq8elQ== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO4P265MB6525 Provide `read_val` and `write_val` that allow I/O views to be accessed when they're narrowed down to just views of primitives. This is used to provide `io_read!` and `io_write!` macros, which are generalized version of current `dma_read!` and `dma_write!` macro that work for all types that implement `Io`. Note though `io_read!` and `io_write!` only works if backend implements `IoCapable` for the type; which is typically only implemented for atomically accessible primitives. `dma_read!` and `dma_write!` currently supports them via `read_volatile` and `write_volatile`; this can be undesirable for aggregates as LLVM may turn them to multiple instructions to access parts and re-assemble, even if they could be combined to a single instruction. Thus, `io_read!()` and `io_write!()` does not fully replace `dma_read!()` and `dma_write!()` in this scenario. The ability to read/write aggregates (when atomicity is of no concern) is better served with copying primitives (e.g. memcpy_{from,to}io). Signed-off-by: Gary Guo Suggested-by: Danilo Krummrich --- rust/kernel/io.rs | 104 ++++++++++++++++++++++++++++++++++++++++++++++++++= ++++ 1 file changed, 104 insertions(+) diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index a418c8cbb031..f64ca2202ff2 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -347,6 +347,50 @@ fn try_cast(self) -> Result<::View<'a, U>> Ok(unsafe { Self::Backend::project_view(view, ptr.cast()) }) } =20 + /// Read a value from I/O. + /// + /// This only works for primitives supported by the I/O backend. + /// + /// # Examples + /// + /// ```no_run + /// # use kernel::io::*; + /// # fn test_read_val(mmio: Mmio<'_, u32>) { + /// // let mmio: Mmio<'_, u32>; + /// let val: u32 =3D mmio.read_val(); + /// # } + /// ``` + #[inline] + fn read_val(self) -> Self::Target + where + Self::Backend: IoCapable, + Self::Target: Sized, + { + Self::Backend::io_read(self.as_view()) + } + + /// Write a value to I/O. + /// + /// This only works for primitives supported by the I/O backend. + /// + /// # Examples + /// + /// ```no_run + /// # use kernel::io::*; + /// # fn test_write_val(mmio: Mmio<'_, u32>) { + /// // let mmio: Mmio<'_, u32>; + /// mmio.write_val(1u32); + /// # } + /// ``` + #[inline] + fn write_val(self, value: Self::Target) + where + Self::Backend: IoCapable, + Self::Target: Sized, + { + Self::Backend::io_write(self.as_view(), value) + } + /// Returns a view for a given `offset`, performing compile-time bound= checks. // Always inline to optimize out error path of `build_assert`. #[inline(always)] @@ -1232,3 +1276,63 @@ macro_rules! io_project { } #[doc(inline)] pub use crate::io_project; + +/// Read from I/O memory. +/// +/// The syntax is of form `io_read!(io, proj)` where `io` is an expression= to a type that +/// implements [`Io`] and `proj` is a [projection specification](kernel::p= tr::project!). +/// +/// # Examples +/// +/// ``` +/// struct MyStruct { field: u32, } +/// +/// # fn test(mmio: kernel::io::Mmio<'_, [MyStruct]>) -> Result { +/// // let mmio: Mmio<'_, [MyStruct]>; +/// let field: u32 =3D kernel::io::io_read!(mmio, [try: 2].field); +/// # Ok::<(), Error>(()) } +/// ``` +#[macro_export] +#[doc(hidden)] +macro_rules! io_read { + ($io:expr, $($proj:tt)*) =3D> { + $crate::io::Io::read_val($crate::io_project!($io, $($proj)*)) + }; +} +#[doc(inline)] +pub use crate::io_read; + +/// Writes to I/O memory. +/// +/// The syntax is of form `io_write!(io, proj, val)` where `io` is an expr= ession to a type that +/// implements [`Io`] and `proj` is a [projection specification](kernel::p= tr::project!), +/// and `val` is the value to be written to the projected location. +/// +/// # Examples +/// +/// ``` +/// struct MyStruct { field: u32, } +/// +/// # fn test(mmio: kernel::io::Mmio<'_, [MyStruct]>) -> Result { +/// // let mmio: Mmio<'_, [MyStruct]>; +/// kernel::io::io_write!(mmio, [try: 2].field, 10); +/// # Ok::<(), Error>(()) } +/// ``` +#[macro_export] +#[doc(hidden)] +macro_rules! io_write { + (@parse [$io:expr] [$($proj:tt)*] [, $val:expr]) =3D> { + $crate::io::Io::write_val($crate::io_project!($io, $($proj)*), $va= l) + }; + (@parse [$io:expr] [$($proj:tt)*] [.$field:tt $($rest:tt)*]) =3D> { + $crate::io_write!(@parse [$io] [$($proj)* .$field] [$($rest)*]) + }; + (@parse [$io:expr] [$($proj:tt)*] [[$flavor:ident: $index:expr] $($res= t:tt)*]) =3D> { + $crate::io_write!(@parse [$io] [$($proj)* [$flavor: $index]] [$($r= est)*]) + }; + ($io:expr, $($rest:tt)*) =3D> { + $crate::io_write!(@parse [$io] [] [$($rest)*]) + }; +} +#[doc(inline)] +pub use crate::io_write; --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from CWXP265CU010.outbound.protection.outlook.com (mail-ukwestazon11022106.outbound.protection.outlook.com [52.101.101.106]) (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 95ED7496904; Thu, 11 Jun 2026 16:28:48 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.101.106 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195331; cv=fail; b=JlcDN77fc4ItXW0qUAYGPFmlcrYwInR85fCIELIhYw/cIN5iT54eSQsNRtRA85hJDc19q/1gypfnMc3SYlVomILDvJ8cQJuUs+hNtynC8I3Pp1yrugPL1jymHUDM2Q8sLyfYM5ILAtgg1FFqXhzTlCohDzKjK60KkKKb3AqHC4c= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195331; c=relaxed/simple; bh=X3jtfWZLQGJZh2g9tCEqgAxb4lmWw01CX+lOBYGY4qM=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=CRSePjkLGVza3b04Pk8keMw07dvsexeWXo4ZaW9czxmiZ9PNF7Vuizh883kMe5Wk1R1lGEcpDC6aqoQ5aJGGak21OvlYC3xGEmNpsvd6XBJ9zJBkhjRQbXUUoYWHNgPh8H/RZ7qdTq94woE2jFcUL68z3vXOXH1JrXN0Lafpv4c= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=LUPORnRi; arc=fail smtp.client-ip=52.101.101.106 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="LUPORnRi" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=davStuv447juijMlpIMX2H35gRyb+M9knOEvr/E77taSjsZdHm3POmqc7YRE7MCbTjNVtfbOWwA2c7TkN9OYDZGuGQBtvQO3Ih8DheH8pJxaPM4VSidr0nClODbbQBIVb5OXIekzoaTp0OrgxFotMquJCjgLcjqrp87E+K2YKRuAhPjJMMtuugFJ7mX81nGmMkjn+lN3Fhioi836qSPpQLQijUB0Ep+DSU5OMpx9cUrbutuVt2ijsxjbrdA1PRqOrq2IT/lhm2hes9GmnKz8xMmkvNaJKxilY3vd7frNc46ydtRoD+Zn/EdiAKN8NoiiG99Xw2VfYj5oCncf1OrAFA== 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=VvP3V1N2DDGsrmatTSvhoZJuRmdEBJem5u3DqqZsDrA=; b=TstVJKy3Eq2XsUD7M+vyKYFirPwiOp7N3f4eLNvao4AUL598VBPijTiaHO7Y8rq4Y3sZ2mETae9whNllct+ZCanJj5BpuW+MO8stSD9ffA+KP+utobua/Akcb/2iKd7TZGpnALGWJKRu7cDZYTYuPwSExS9ABLiRmjNhSk14BETbjFDYOofmuQiX4OD9RIRPopUM6nSz8OHQ+3trigrBn8PwdRfwRcPHBo3hrPLdWtdZgEqtIOZyLcyjTzTFHPZi4n2aesNEsyICdsO2A9ckbIrQurfG98IfvMyi3Ff7UMJqHCUrpcAhgNlqK0rsnoXsrvtwJ6qMNgR3poOUzia8xw== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=VvP3V1N2DDGsrmatTSvhoZJuRmdEBJem5u3DqqZsDrA=; b=LUPORnRiuk8tgHYfr36u0hLjEZS0OWeF5VmmzX2tEJUIV2xrTj9b5WjB1/fWX4ibJnSnHeBKgc5FOBC9ze910bxhYxm3a0pOXPRRT5fvvTasFgGcazA3rmZwdBa3N/fFrMdyMBBpOTrvPe/PAoNklzFL838fsduYPDJubtk0eiY= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO4P265MB6525.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:2e7::9) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.11; Thu, 11 Jun 2026 16:28:32 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:32 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:19 +0100 Subject: [PATCH v4 17/20] gpu: nova-core: use I/O projection for cleaner encapsulation Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-17-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195301; l=13099; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=X3jtfWZLQGJZh2g9tCEqgAxb4lmWw01CX+lOBYGY4qM=; b=T4mmhjhEPj1vEDa7YClxNoxvGs6OTJpkZxYSTS/wg0AHAVW7QE93eZ0zmH1Qm3EGITH1OpzBE QcGSW2Vgyb+Dp462CIB8qN7tfYEur4Rjja1YoxC/QutTM4buZqn2v+4 X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO4P265MB6525:EE_ X-MS-Office365-Filtering-Correlation-Id: d4c4056e-c6dc-40ea-78d4-08dec7d67a82 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|23010399003|376014|7416014|366016|1800799024|10070799003|921020|6133799003|56012099006|3023799007|22082099003|18002099003; X-Microsoft-Antispam-Message-Info: hY6oSpQDGZDkqNtTjH++bTcLTSSaizBz4sa6Vv5CF6r6DLs/i1jamB2WFK59J3fElDa218lJqZYwX66zp2o7DDzG9WAEyjhjw/bBar/3J8EuI0w+yznneeKZ8zMfsukiJUB9rNib/F62+k7RMSMFD3l8NP8+g+dioizf8dFhXDjj5///2qRQU6mG0irbbTCg7Pc0KmyMGq5a0AmlrsP8hXzMLGE6RMBCS/RZo+l3GXfwCee2Y36PWA3ZU7pMnIOfY8ddOZn5rrDA9+pwVwU9WTfZceOPlSJK222I3D4oGZ1yj1UiPp9cj7zmDGRm+NbSmuytevSrYl5xhEQVYMbrdtOvhIbh6Usxi2JZLFlUCdFemd+RRBNlA7deNt+TFS85JofTRBQ41nFfCozvt2uXh0/HZRKmCpAwpf7ihb61caQQ/uqqa60CJW9D8pv/DaVJ5Cdx1SbrfruvMQJSKIw6BRU+eFTBaZcs5s5z9On8M/Aho3Vk328JvIflULMHQXOKI87WaqOXImLhicpfFwoquTDUjHzZJRoHdwXClbNIEYyW0wSRBP7xVvWIIvloRb6FBuygngU7WIpHf8fe3HFik3TC7k1vlgWRAC4J2QvceFcEmMsWk+vVKKqwbJbhvfQGimD3PsFBFgNFchrQnYls3+FCqmQotu/CbXp9UHV9VDsOkFi7pNhTQZoRW7mgSPpxlIWXtikJdYjRXInxWDU+Fx9uO7KoTCrxEUIAqBlp+IQ= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(23010399003)(376014)(7416014)(366016)(1800799024)(10070799003)(921020)(6133799003)(56012099006)(3023799007)(22082099003)(18002099003);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?NjZwM3ZmYkpFYVJhRGcxM0lnQW1GeDJUalJzVjRma1oyVDROODJibmczRzFv?= =?utf-8?B?N05yUUZuRENiU3pWaFJ3TWE2aDNXam5oMDc4M2N6UjhKNmo2MG00L3ZUYlQy?= =?utf-8?B?MzhaT20ybGY4L1VMRE5mTU9sUDRpeWpGdE45ekl5dk9TK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ZEdnK1JJMXQxdmpQcWFyRHZZdjZidTlRWm1iVHhtMzJ2eEx3KzF2dUNKR24v?= =?utf-8?B?T2I1eUUyM3VGamU3VVlNdzlEVi9CbEoxa2E2aXpsdE1jd2pYNkFBaUpvNG1x?= =?utf-8?B?bjJVQmRYK2RTMGFSSWdxUklybWtSSldJM3Z2TGRrcHAxUHVqbjdBbzJUTDFT?= =?utf-8?B?WVVtenFZY2hUMU1PZHczR0Q5SWIrZHV2L1dtOUNETTI3Vm9rTDVwaVAzeU1V?= =?utf-8?B?MTA4QWJVUHRjZnVpV3Jac1NGaS9Vc0Z5OVlXUDV0ZVJEdEpvNzRMcFBMZW1R?= =?utf-8?B?d2htZGlxRk1OTmNlRHljVUZjUUdMVHoxSFZ2Z2wwcWhQRjgzTTF4ZlRnbW40?= =?utf-8?B?RytzazNSbWF5M1lQSGtYeTBpaUx5eHFQMG5ja05XVE1MMlhvZ0dIUT09?= X-OriginatorOrg: garyguo.net X-MS-Exchange-CrossTenant-Network-Message-Id: d4c4056e-c6dc-40ea-78d4-08dec7d67a82 X-MS-Exchange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:32.6329 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: FRIIwG40BA1rvEScOSIK4564fqL2ktnPr8xrLhSS+Hp2v4/F/rY4WbFQEQEI8nIm6IY8fV3j+yBmF/2jo2wewA== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO4P265MB6525 Use `io_project!` for PTE array and message queues to restore the proper encapsulation. The remaining `dma_read!` and `dma_write!` is now only acting on primitives; thus replace by `io_read!` and `io_write!`. Signed-off-by: Gary Guo Suggested-by: Danilo Krummrich --- drivers/gpu/nova-core/gsp.rs | 53 ++++++++++++------------- drivers/gpu/nova-core/gsp/cmdq.rs | 66 +++++++++++++++++-------------- drivers/gpu/nova-core/gsp/fw.rs | 82 +++++++++++++----------------------= ---- 3 files changed, 90 insertions(+), 111 deletions(-) diff --git a/drivers/gpu/nova-core/gsp.rs b/drivers/gpu/nova-core/gsp.rs index 69175ca3315c..cfa7553cd820 100644 --- a/drivers/gpu/nova-core/gsp.rs +++ b/drivers/gpu/nova-core/gsp.rs @@ -9,14 +9,16 @@ dma::{ Coherent, CoherentBox, + CoherentView, DmaAddress, // }, + io::{ + io_project, + io_write, + Io, // + }, pci, - prelude::*, - transmute::{ - AsBytes, - FromBytes, // - }, // + prelude::*, // }; =20 pub(crate) mod cmdq; @@ -48,21 +50,21 @@ =20 /// Array of page table entries, as understood by the GSP bootloader. #[repr(C)] +#[derive(FromBytes, IntoBytes)] struct PteArray([u64; NUM_ENTRIES]); =20 -/// SAFETY: arrays of `u64` implement `FromBytes` and we are but a wrapper= around one. -unsafe impl FromBytes for PteArray = {} - -/// SAFETY: arrays of `u64` implement `AsBytes` and we are but a wrapper a= round one. -unsafe impl AsBytes for PteArray {} - impl PteArray { - /// Returns the page table entry for `index`, for a mapping starting a= t `start`. - // TODO: Replace with `IoView` projection once available. - fn entry(start: DmaAddress, index: usize) -> Result { - start - .checked_add(num::usize_as_u64(index) << GSP_PAGE_SHIFT) - .ok_or(EOVERFLOW) + /// Initialize a new page table array mapping `NUM_PAGES` GSP pages st= arting at address `start`. + fn init(view: CoherentView<'_, Self>, start: DmaAddress) -> Result<()>= { + for i in 0..NUM_PAGES { + io_write!(view, .0[build: i], + start + .checked_add(num::usize_as_u64(i) << GSP_PAGE_SHIFT) + .ok_or(EOVERFLOW)? + ); + } + + Ok(()) } } =20 @@ -89,17 +91,12 @@ fn new(dev: &device::Device) -> Result { =20 let start_addr =3D obj.0.dma_handle(); =20 - // SAFETY: `obj` has just been created and we are its sole user. - let pte_region =3D unsafe { - &mut obj.0.as_mut()[size_of::()..][..RM_LOG_BUFFER_NUM_PA= GES * size_of::()] - }; - - // Write values one by one to avoid an on-stack instance of `PteAr= ray`. - for (i, chunk) in pte_region.chunks_exact_mut(size_of::()).en= umerate() { - let pte_value =3D PteArray::<0>::entry(start_addr, i)?; - - chunk.copy_from_slice(&pte_value.to_ne_bytes()); - } + let pte_view =3D io_project!( + obj.0, + [build: size_of::()..][build: ..RM_LOG_BUFFER_NUM_PAGES *= size_of::()] + ) + .try_cast::>()?; + PteArray::init(pte_view, start_addr)?; =20 Ok(obj) } diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/= cmdq.rs index 070de0731e95..c34b48961496 100644 --- a/drivers/gpu/nova-core/gsp/cmdq.rs +++ b/drivers/gpu/nova-core/gsp/cmdq.rs @@ -2,16 +2,23 @@ =20 mod continuation; =20 -use core::mem; +use core::{ + mem, + sync::atomic::{ + fence, + Ordering, // + }, +}; =20 use kernel::{ device, dma::{ Coherent, + CoherentBox, DmaAddress, // }, - dma_write, io::{ + io_project, poll::read_poll_timeout, Io, // }, @@ -171,20 +178,18 @@ struct MsgqData { #[repr(C)] // There is no struct defined for this in the open-gpu-kernel-source heade= rs. // Instead it is defined by code in `GspMsgQueuesInit()`. -// TODO: Revert to private once `IoView` projections replace the `gsp_mem`= module. -pub(super) struct Msgq { +struct Msgq { /// Header for sending messages, including the write pointer. - pub(super) tx: MsgqTxHeader, + tx: MsgqTxHeader, /// Header for receiving messages, including the read pointer. - pub(super) rx: MsgqRxHeader, + rx: MsgqRxHeader, /// The message queue proper. msgq: MsgqData, } =20 /// Structure shared between the driver and the GSP and containing the com= mand and message queues. #[repr(C)] -// TODO: Revert to private once `IoView` projections replace the `gsp_mem`= module. -pub(super) struct GspMem { +struct GspMem { /// Self-mapping page table entries. ptes: PteArray<{ Self::PTE_ARRAY_SIZE }>, /// CPU queue: the driver writes commands here, and the GSP reads them= . It also contains the @@ -192,13 +197,13 @@ pub(super) struct GspMem { /// index into the GSP queue. /// /// This member is read-only for the GSP. - pub(super) cpuq: Msgq, + cpuq: Msgq, /// GSP queue: the GSP writes messages here, and the driver reads them= . It also contains the /// write and read pointers that the GSP updates. This means that the = read pointer here is an /// index into the CPU queue. /// /// This member is read-only for the driver. - pub(super) gspq: Msgq, + gspq: Msgq, } =20 impl GspMem { @@ -232,20 +237,12 @@ fn new(dev: &device::Device) -> Result= { const MSGQ_SIZE: u32 =3D num::usize_into_u32::<{ size_of::()= }>(); const RX_HDR_OFF: u32 =3D num::usize_into_u32::<{ mem::offset_of!(= Msgq, rx) }>(); =20 - let gsp_mem =3D Coherent::::zeroed(dev, GFP_KERNEL)?; - - let start =3D gsp_mem.dma_handle(); - // Write values one by one to avoid an on-stack instance of `PteAr= ray`. - for i in 0..GspMem::PTE_ARRAY_SIZE { - dma_write!(gsp_mem, .ptes.0[build: i], PteArray::<0>::entry(st= art, i)?); - } + let mut gsp_mem =3D CoherentBox::::zeroed(dev, GFP_KERNEL)= ?; + gsp_mem.cpuq.tx =3D MsgqTxHeader::new(MSGQ_SIZE, RX_HDR_OFF, MSGQ_= NUM_PAGES); + gsp_mem.cpuq.rx =3D MsgqRxHeader::new(); =20 - dma_write!( - gsp_mem, - .cpuq.tx, - MsgqTxHeader::new(MSGQ_SIZE, RX_HDR_OFF, MSGQ_NUM_PAGES) - ); - dma_write!(gsp_mem, .cpuq.rx, MsgqRxHeader::new()); + let gsp_mem: Coherent<_> =3D gsp_mem.into(); + PteArray::init(io_project!(gsp_mem, .ptes), gsp_mem.dma_handle())?; =20 Ok(Self(gsp_mem)) } @@ -406,7 +403,7 @@ fn allocate_command(&mut self, size: usize, timeout: De= lta) -> Result u32 { - super::fw::gsp_mem::gsp_write_ptr(&self.0) + MsgqTxHeader::write_ptr(io_project!(self.0, .gspq.tx)) % MSGQ_NUM_= PAGES } =20 // Returns the index of the memory page the GSP will read the next com= mand from. @@ -415,7 +412,7 @@ fn gsp_write_ptr(&self) -> u32 { // // - The returned value is within `0..MSGQ_NUM_PAGES`. fn gsp_read_ptr(&self) -> u32 { - super::fw::gsp_mem::gsp_read_ptr(&self.0) + MsgqRxHeader::read_ptr(io_project!(self.0, .gspq.rx)) % MSGQ_NUM_P= AGES } =20 // Returns the index of the memory page the CPU can read the next mess= age from. @@ -424,12 +421,18 @@ fn gsp_read_ptr(&self) -> u32 { // // - The returned value is within `0..MSGQ_NUM_PAGES`. fn cpu_read_ptr(&self) -> u32 { - super::fw::gsp_mem::cpu_read_ptr(&self.0) + MsgqRxHeader::read_ptr(io_project!(self.0, .cpuq.rx)) % MSGQ_NUM_P= AGES } =20 // Informs the GSP that it can send `elem_count` new pages into the me= ssage queue. fn advance_cpu_read_ptr(&mut self, elem_count: u32) { - super::fw::gsp_mem::advance_cpu_read_ptr(&self.0, elem_count) + let rx =3D io_project!(self.0, .cpuq.rx); + let rptr =3D MsgqRxHeader::read_ptr(rx).wrapping_add(elem_count) %= MSGQ_NUM_PAGES; + + // Ensure read pointer is properly ordered. + fence(Ordering::SeqCst); + + MsgqRxHeader::set_read_ptr(rx, rptr) } =20 // Returns the index of the memory page the CPU can write the next com= mand to. @@ -438,12 +441,17 @@ fn advance_cpu_read_ptr(&mut self, elem_count: u32) { // // - The returned value is within `0..MSGQ_NUM_PAGES`. fn cpu_write_ptr(&self) -> u32 { - super::fw::gsp_mem::cpu_write_ptr(&self.0) + MsgqTxHeader::write_ptr(io_project!(self.0, .cpuq.tx)) % MSGQ_NUM_= PAGES } =20 // Informs the GSP that it can process `elem_count` new pages from the= command queue. fn advance_cpu_write_ptr(&mut self, elem_count: u32) { - super::fw::gsp_mem::advance_cpu_write_ptr(&self.0, elem_count) + let tx =3D io_project!(self.0, .cpuq.tx); + let wptr =3D MsgqTxHeader::write_ptr(tx).wrapping_add(elem_count) = % MSGQ_NUM_PAGES; + MsgqTxHeader::set_write_ptr(tx, wptr); + + // Ensure all command data is visible before triggering the GSP re= ad. + fence(Ordering::SeqCst); } } =20 diff --git a/drivers/gpu/nova-core/gsp/fw.rs b/drivers/gpu/nova-core/gsp/fw= .rs index 4db0cfa4dc4d..b0e7de328eaf 100644 --- a/drivers/gpu/nova-core/gsp/fw.rs +++ b/drivers/gpu/nova-core/gsp/fw.rs @@ -10,7 +10,14 @@ use core::ops::Range; =20 use kernel::{ - dma::Coherent, + dma::{ + Coherent, + CoherentView, // + }, + io::{ + io_read, + io_write, // + }, prelude::*, ptr::{ Alignable, @@ -44,59 +51,6 @@ }, }; =20 -// TODO: Replace with `IoView` projections once available. -pub(super) mod gsp_mem { - use core::sync::atomic::{ - fence, - Ordering, // - }; - - use kernel::{ - dma::Coherent, - dma_read, - dma_write, // - }; - - use crate::gsp::cmdq::{ - GspMem, - MSGQ_NUM_PAGES, // - }; - - pub(in crate::gsp) fn gsp_write_ptr(qs: &Coherent) -> u32 { - dma_read!(qs, .gspq.tx.0.writePtr) % MSGQ_NUM_PAGES - } - - pub(in crate::gsp) fn gsp_read_ptr(qs: &Coherent) -> u32 { - dma_read!(qs, .gspq.rx.0.readPtr) % MSGQ_NUM_PAGES - } - - pub(in crate::gsp) fn cpu_read_ptr(qs: &Coherent) -> u32 { - dma_read!(qs, .cpuq.rx.0.readPtr) % MSGQ_NUM_PAGES - } - - pub(in crate::gsp) fn advance_cpu_read_ptr(qs: &Coherent, coun= t: u32) { - let rptr =3D cpu_read_ptr(qs).wrapping_add(count) % MSGQ_NUM_PAGES; - - // Ensure read pointer is properly ordered. - fence(Ordering::SeqCst); - - dma_write!(qs, .cpuq.rx.0.readPtr, rptr); - } - - pub(in crate::gsp) fn cpu_write_ptr(qs: &Coherent) -> u32 { - dma_read!(qs, .cpuq.tx.0.writePtr) % MSGQ_NUM_PAGES - } - - pub(in crate::gsp) fn advance_cpu_write_ptr(qs: &Coherent, cou= nt: u32) { - let wptr =3D cpu_write_ptr(qs).wrapping_add(count) % MSGQ_NUM_PAGE= S; - - dma_write!(qs, .cpuq.tx.0.writePtr, wptr); - - // Ensure all command data is visible before triggering the GSP re= ad. - fence(Ordering::SeqCst); - } -} - /// Maximum size of a single GSP message queue element in bytes. pub(crate) const GSP_MSG_QUEUE_ELEMENT_SIZE_MAX: usize =3D num::u32_as_usize(bindings::GSP_MSG_QUEUE_ELEMENT_SIZE_MAX); @@ -720,6 +674,16 @@ pub(crate) fn new(msgq_size: u32, rx_hdr_offset: u32, = msg_count: u32) -> Self { entryOff: num::usize_into_u32::(), }) } + + /// Returns the value of the write pointer for this queue. + pub(crate) fn write_ptr(this: CoherentView<'_, Self>) -> u32 { + io_read!(this, .0.writePtr) + } + + /// Sets the value of the write pointer for this queue. + pub(crate) fn set_write_ptr(this: CoherentView<'_, Self>, val: u32) { + io_write!(this, .0.writePtr, val) + } } =20 // SAFETY: Padding is explicit and does not contain uninitialized data. @@ -735,6 +699,16 @@ impl MsgqRxHeader { pub(crate) fn new() -> Self { Self(Default::default()) } + + /// Returns the value of the read pointer for this queue. + pub(crate) fn read_ptr(this: CoherentView<'_, Self>) -> u32 { + io_read!(this, .0.readPtr) + } + + /// Sets the value of the read pointer for this queue. + pub(crate) fn set_read_ptr(this: CoherentView<'_, Self>, val: u32) { + io_write!(this, .0.readPtr, val) + } } =20 // SAFETY: Padding is explicit and does not contain uninitialized data. --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from CWXP265CU010.outbound.protection.outlook.com (mail-ukwestazon11022126.outbound.protection.outlook.com [52.101.101.126]) (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 A3EE14A2E10; Thu, 11 Jun 2026 16:28:49 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.101.126 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195332; cv=fail; b=TPBVpaeDRE+Iz/y4GS/f726JwR2dYZYSfZwM/x0q0Xor90+AdtGEtTuLDb37kCeeGTNmyg3FmGJmLTKCt++lrJghkRM8yWyl/bHqJFESIu92ogyweQzM0wBaIy0Jw5ArxH3IUb2zrZv0FQjnYY+QrJ+mZF6AzEl1ckG42541wk4= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195332; c=relaxed/simple; bh=jwpOL+8onvWtIguzV59vIP2zyg5diaxn32RlHDnn1Gg=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=H0kZf0Wi4KDumFoGKJrvTN90vQDzW/Xsu/8OYxsu1IOvuRxtNvGG1us5uHVWx1qADAsZAx63SlXoBPhae+HQfyTWE3Kit5cM6zR+ck2cm91SrAYW/b8fvFo+/pmoqpp2ajuUS4IvnH16jbhTxukIZNcGiySr1ru5l0ssg7GtFTM= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=uGPObIUx; arc=fail smtp.client-ip=52.101.101.126 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="uGPObIUx" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=IVdmpd3JKygNH4wHQT82r0pY6N3nF23WcofrLTz2zmKnTO/mU12qCJv1z7mFPKrbE0euk5qmaMS4dU5bkpb5tcHKGeTPDnibJNNk54l2u2lwKjMVr8T+H/JfDdpWrMGweG5iRELIrXfla4qZX/jWEnBPrxNqsRZe6nMrfBK/GUU2mjfxtgqXeFEl8/VPX6iLRvP1nAagrus//VVGI3IkhG+xjwAUXLFx3He5y1/Dt8GfG/e4I1rhbMlRumF45VDTVtDMtpkSvq8M15TQ7dvQnfJwA+cNmPqcvvCz1pkkLdOp9mwvUvh3chfrsFdabSSE1XfxJkjRIkdeUJrLowVKJQ== 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=fCVwIbTNS4Ld6i4HIC/5quYTYSjv320ziVokMa2TFXw=; b=P2nakvRWa2n+VOx4VqDTEs6sBB35mzc5uALF9EABkb+6uej65QYdHEQyuau1drhoXKhdJRO4LodTHGMsvTiiQTZsr1Bj6jf6oeqyGb+zOmHs71ln9eIK2k8PTOrxN+W98/VJGJToRbUgSmBwgtzoLjfXPUz4vi6PqMPfr7z128QC25C04s6EwEFqo3Jt5U6TR0T6dGzlrGZJ4PawOx1n5SEiL36vs99Flka6Mo81vKbG2CVGvmx4AnpVQ3JhHfTaKmYwUcJkBKtmXEtxr48v4VWVvlgn/4DyIelshB3trJRGzgr3nOu72spB3yzaBzraRYtAQLR/fHOYuUNhBEwOmw== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=fCVwIbTNS4Ld6i4HIC/5quYTYSjv320ziVokMa2TFXw=; b=uGPObIUxkBtCGG3a9gtcIsDh5D9+k5GntMuGYzp0CUONlDBK/mVuwcyEK6dR6TN9FXsekagajwtcJCoFVbuIjflJCYOpiSZbTKo2/EZ1e6Iz6T9Kp+11ixq29dosYWGZWNM5AJRDdbqqUoopOb3WSfbYTRBGYD18qRjYvSec7uA= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO4P265MB6525.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:2e7::9) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.11; Thu, 11 Jun 2026 16:28:33 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:33 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:20 +0100 Subject: [PATCH v4 18/20] rust: dma: drop `dma_read!` and `dma_write!` API Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-18-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195302; l=8864; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=jwpOL+8onvWtIguzV59vIP2zyg5diaxn32RlHDnn1Gg=; b=Dw/uRpp9JFOqgDpEN11O2fB0xrpBa1HLOGCIiwu+lyBAguYvVvy3Ieo2Rbqc4wV7wfQACInli SogeJHP1suAAn0djAB0PAeEnwF1uiDaFYvXnTe8V/P28wder8/MSSpS X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO4P265MB6525:EE_ X-MS-Office365-Filtering-Correlation-Id: 4a895751-d97b-4b54-6b55-08dec7d67ada X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|23010399003|376014|7416014|366016|1800799024|10070799003|921020|6133799003|56012099006|3023799007|5023799004|22082099003|18002099003; X-Microsoft-Antispam-Message-Info: 2/zg+cr6djZnOu/sNg5fmxH0tu/wdwdQ8jHBiWBn7fIMES9gstF5a8/Tbnrczrb1uN/REqvqSPTVOXPl/5n1F0b9mDUl3KmmrzhpFpSPeqGL0i9b8TKW2LuQ1rUBbgyEm/1gi+p+ijG4SomabcxG7zDAIxMNgskCiUj2oshbE21/aByI4AdyfheACRpXCsrZNaHnsyRLJFIKgq0f/YJh35p1nV7aI8ewuq0L8JpF0HD2Gylj7B75Ec1SjEKvR5NwBowD9nOxWD9W4fUMtAMqFqweJwYaLZW0xzWD/4PDCGhexTtFqs4uk4QadBSJdvruXUm7LvHnnh5ihekGCPmoHieMmaGXO5j2ZDKs9F3iCGSWwiblvjiLPMKh9xSaamyTBJ567YUcA2/nu9DYcvqIWUEg6UFWZR06ogzTV60xMDh1kSWrllaUyXcpKhrMXxy1FiY8N9d7Xghq/6g0D+/YRPnFvUTKzsMxCftzmMrwYgEVRg7p3tMFVXYEQIjXafZbWDjGl+IqDECxNDO4FQnzFEbBizpt8DVX5p3neWk6nGnKQtRoiSCbjxONCfgMtnxxDli4LmoFMjckqTKBgjoTcOIE07ntysysPU0M/MUIMDtDBdZ6IHz8Lw/lVo0pNX+MCzFA5Isv3Cl0dMxYC2GgKYFYqVBmiABt7ztB563XujEbg/6P+BtsQNT3xpLma1iJSAl9AL0dMOIieuJT2ueAMzZF9givcBSAFMWKgCf09F0= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(23010399003)(376014)(7416014)(366016)(1800799024)(10070799003)(921020)(6133799003)(56012099006)(3023799007)(5023799004)(22082099003)(18002099003);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?R1RLbHowV01hVEV4clo1eXkzcFBqcWVsOXFWUnh5aVJoWG43dGJlQlJ2MzFJ?= =?utf-8?B?UUlVcnRRT0lkZ0tVdTdXVjJCTThFTTg3aUpZR1hqbkpzOVRwNitZS284dGNv?= =?utf-8?B?L3cvT2VGbDlvNlJzYjFScGlMOWQ2RXEzRGJyeWpBU0oxREpnUk5od0xWQ2RB?= =?utf-8?B?cUNUck1VY1Mxc1hsSEFGSFRhc3pSVS84dS9EMUtlOWZYdldhL20yNHNkWDcr?= =?utf-8?B?NlBqOWhyc0VvSXNvSWk5dEZHWW9oWm5hQ0p3Tm5FTmh1Skp5b1FUMjhDcFFt?= =?utf-8?B?a1JaOE1GSTVRNjdhbkdXS1NDZ2FkZnlqdWp3V0cvdzl6SytNcnp0T2tMSTFU?= =?utf-8?B?cjR4WW93T1pv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4Vld6YWtUbG93NVFxNVh6?= =?utf-8?B?M1Q4Q3NzVGpzbHRiN1dPN3pQSFRVRDdyQjQzanBMVmF6WjZ6RWhnV1hVd0hH?= =?utf-8?B?Y0QxWVNEZm5sU3ViYTY4azIwVktxWWdkTmNFNmIyM3g3NWIvOE1SbWM0ZnpE?= =?utf-8?B?YXYxY1gxaklvaUhMT0p5Zkl5S3Bwdis0bkU5S3dnYms1UXFMbU1Ddz09?= X-OriginatorOrg: garyguo.net X-MS-Exchange-CrossTenant-Network-Message-Id: 4a895751-d97b-4b54-6b55-08dec7d67ada X-MS-Exchange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:33.2185 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: O2av2+OxSKkLNV0H+7DA+hVgyuhuw62B7D+LbjNM6SdqErgAeXnyRmrkW51aN0ExCnowD46Rs7x4WmADLeBCAA== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO4P265MB6525 The primitive read/write use case is covered by the `io_read!` and `io_write!` macro. The non-primitive use case was finicky; they should either be achieved using `CoherentBox` or `as_ref()/as_mut()` to assert the lack of concurrent access, or should be using memcpy-like APIs to express the non-atomic and tearable nature. Reviewed-by: Andreas Hindborg Signed-off-by: Gary Guo Suggested-by: Danilo Krummrich --- rust/kernel/dma.rs | 128 -------------------------------------------= ---- samples/rust/rust_dma.rs | 13 ++--- 2 files changed, 7 insertions(+), 134 deletions(-) diff --git a/rust/kernel/dma.rs b/rust/kernel/dma.rs index ab6504910e4f..0ff4cce8e809 100644 --- a/rust/kernel/dma.rs +++ b/rust/kernel/dma.rs @@ -661,52 +661,6 @@ pub unsafe fn as_mut(&self) -> &mut T { // SAFETY: per safety requirement. unsafe { &mut *self.as_mut_ptr() } } - - /// Reads the value of `field` and ensures that its type is [`FromByte= s`]. - /// - /// # Safety - /// - /// This must be called from the [`dma_read`] macro which ensures that= the `field` pointer is - /// validated beforehand. - /// - /// Public but hidden since it should only be used from [`dma_read`] m= acro. - #[doc(hidden)] - pub unsafe fn field_read(&self, field: *const F) -> F { - // SAFETY: - // - By the safety requirements field is valid. - // - Using read_volatile() here is not sound as per the usual rule= s, the usage here is - // a special exception with the following notes in place. When dea= ling with a potential - // race from a hardware or code outside kernel (e.g. user-space pr= ogram), we need that - // read on a valid memory is not UB. Currently read_volatile() is = used for this, and the - // rationale behind is that it should generate the same code as RE= AD_ONCE() which the - // kernel already relies on to avoid UB on data races. Note that t= he usage of - // read_volatile() is limited to this particular case, it cannot b= e used to prevent - // the UB caused by racing between two kernel functions nor do the= y provide atomicity. - unsafe { field.read_volatile() } - } - - /// Writes a value to `field` and ensures that its type is [`AsBytes`]. - /// - /// # Safety - /// - /// This must be called from the [`dma_write`] macro which ensures tha= t the `field` pointer is - /// validated beforehand. - /// - /// Public but hidden since it should only be used from [`dma_write`] = macro. - #[doc(hidden)] - pub unsafe fn field_write(&self, field: *mut F, val: F) { - // SAFETY: - // - By the safety requirements field is valid. - // - Using write_volatile() here is not sound as per the usual rul= es, the usage here is - // a special exception with the following notes in place. When dea= ling with a potential - // race from a hardware or code outside kernel (e.g. user-space pr= ogram), we need that - // write on a valid memory is not UB. Currently write_volatile() i= s used for this, and the - // rationale behind is that it should generate the same code as WR= ITE_ONCE() which the - // kernel already relies on to avoid UB on data races. Note that t= he usage of - // write_volatile() is limited to this particular case, it cannot = be used to prevent - // the UB caused by racing between two kernel functions nor do the= y provide atomicity. - unsafe { field.write_volatile(val) } - } } =20 impl Coherent { @@ -1265,85 +1219,3 @@ fn as_view(self) -> CoherentView<'a, Self::Target> { } } } - -/// Reads a field of an item from an allocated region of structs. -/// -/// The syntax is of the form `kernel::dma_read!(dma, proj)` where `dma` i= s an expression evaluating -/// to a [`Coherent`] and `proj` is a [projection specification](kernel::p= tr::project!). -/// -/// # Examples -/// -/// ``` -/// use kernel::device::Device; -/// use kernel::dma::{attrs::*, Coherent}; -/// -/// struct MyStruct { field: u32, } -/// -/// // SAFETY: All bit patterns are acceptable values for `MyStruct`. -/// unsafe impl kernel::transmute::FromBytes for MyStruct{}; -/// // SAFETY: Instances of `MyStruct` have no uninitialized portions. -/// unsafe impl kernel::transmute::AsBytes for MyStruct{}; -/// -/// # fn test(alloc: &kernel::dma::Coherent<[MyStruct]>) -> Result { -/// let whole =3D kernel::dma_read!(alloc, [try: 2]); -/// let field =3D kernel::dma_read!(alloc, [panic: 1].field); -/// # Ok::<(), Error>(()) } -/// ``` -#[macro_export] -macro_rules! dma_read { - ($dma:expr, $($proj:tt)*) =3D> {{ - let dma =3D &$dma; - let ptr =3D $crate::ptr::project!( - $crate::dma::Coherent::as_ptr(dma), $($proj)* - ); - // SAFETY: The pointer created by the projection is within the DMA= region. - unsafe { $crate::dma::Coherent::field_read(dma, ptr) } - }}; -} - -/// Writes to a field of an item from an allocated region of structs. -/// -/// The syntax is of the form `kernel::dma_write!(dma, proj, val)` where `= dma` is an expression -/// evaluating to a [`Coherent`], `proj` is a -/// [projection specification](kernel::ptr::project!), and `val` is the va= lue to be written to the -/// projected location. -/// -/// # Examples -/// -/// ``` -/// use kernel::device::Device; -/// use kernel::dma::{attrs::*, Coherent}; -/// -/// struct MyStruct { member: u32, } -/// -/// // SAFETY: All bit patterns are acceptable values for `MyStruct`. -/// unsafe impl kernel::transmute::FromBytes for MyStruct{}; -/// // SAFETY: Instances of `MyStruct` have no uninitialized portions. -/// unsafe impl kernel::transmute::AsBytes for MyStruct{}; -/// -/// # fn test(alloc: &kernel::dma::Coherent<[MyStruct]>) -> Result { -/// kernel::dma_write!(alloc, [try: 2].member, 0xf); -/// kernel::dma_write!(alloc, [panic: 1], MyStruct { member: 0xf }); -/// # Ok::<(), Error>(()) } -/// ``` -#[macro_export] -macro_rules! dma_write { - (@parse [$dma:expr] [$($proj:tt)*] [, $val:expr]) =3D> {{ - let dma =3D &$dma; - let ptr =3D $crate::ptr::project!( - mut $crate::dma::Coherent::as_mut_ptr(dma), $($proj)* - ); - let val =3D $val; - // SAFETY: The pointer created by the projection is within the DMA= region. - unsafe { $crate::dma::Coherent::field_write(dma, ptr, val) } - }}; - (@parse [$dma:expr] [$($proj:tt)*] [.$field:tt $($rest:tt)*]) =3D> { - $crate::dma_write!(@parse [$dma] [$($proj)* .$field] [$($rest)*]) - }; - (@parse [$dma:expr] [$($proj:tt)*] [[$flavor:ident: $index:expr] $($re= st:tt)*]) =3D> { - $crate::dma_write!(@parse [$dma] [$($proj)* [$flavor: $index]] [$(= $rest)*]) - }; - ($dma:expr, $($rest:tt)*) =3D> { - $crate::dma_write!(@parse [$dma] [] [$($rest)*]) - }; -} diff --git a/samples/rust/rust_dma.rs b/samples/rust/rust_dma.rs index 5046b4628d0e..6727c441658a 100644 --- a/samples/rust/rust_dma.rs +++ b/samples/rust/rust_dma.rs @@ -12,6 +12,7 @@ Device, DmaMask, // }, + io::io_read, page, pci, prelude::*, scatterlist::{Owned, SGTable}, @@ -73,11 +74,11 @@ fn probe<'bound>( // SAFETY: There are no concurrent calls to DMA allocation and= mapping primitives. unsafe { pdev.dma_set_mask_and_coherent(mask)? }; =20 - let ca: Coherent<[MyStruct]> =3D - Coherent::zeroed_slice(pdev.as_ref(), TEST_VALUES.len(), G= FP_KERNEL)?; + let mut ca: CoherentBox<[MyStruct]> =3D + CoherentBox::zeroed_slice(pdev.as_ref(), TEST_VALUES.len()= , GFP_KERNEL)?; =20 for (i, value) in TEST_VALUES.into_iter().enumerate() { - kernel::dma_write!(ca, [try: i], MyStruct::new(value.0, va= lue.1)); + ca.init_at(i, MyStruct::new(value.0, value.1))?; } =20 let size =3D 4 * page::PAGE_SIZE; @@ -87,7 +88,7 @@ fn probe<'bound>( =20 Ok(try_pin_init!(Self { pdev: pdev.into(), - ca, + ca: ca.into(), sgt <- sgt, })) }) @@ -97,8 +98,8 @@ fn probe<'bound>( impl DmaSampleDriver { fn check_dma(&self) { for (i, value) in TEST_VALUES.into_iter().enumerate() { - let val0 =3D kernel::dma_read!(self.ca, [panic: i].h); - let val1 =3D kernel::dma_read!(self.ca, [panic: i].b); + let val0 =3D io_read!(self.ca, [panic: i].h); + let val1 =3D io_read!(self.ca, [panic: i].b); =20 assert_eq!(val0, value.0); assert_eq!(val1, value.1); --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from CWXP265CU010.outbound.protection.outlook.com (mail-ukwestazon11022091.outbound.protection.outlook.com [52.101.101.91]) (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 45E0C46AF33; Thu, 11 Jun 2026 16:28:40 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.101.91 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195324; cv=fail; b=Z3KF5dv7W11hAgIVJkKWu/XPgvMKVJZLNyswodDhZYBROrPATs7yDUuHBwZxRYPWI4FYkDnqMJ6SxxE4RIpiiUHL1dehCDXECCYEoGxEuJrOMEDeIdWHLNxVqcWnlhEQS4IA5YQRA3fMVbzXopUorK6UqYXgMeGkMkMKg1uowYA= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195324; c=relaxed/simple; bh=4mlyjPbdnE6Ty78c6hzqGp3ZT8XiEp/nXwOWY38ZETc=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=OQoNJBKgQyn7NTpMThvyS7C02RqOEr3EXk5mUO/2F+pCnqs6n+hkc2VfT57Vs3L90E2szgsLFZHcwh15RY3gIEbCkT951LdFXUOXs/MJboNdPxnUi5VftYRRxjG7pnQ5UEgNxlGG27c3LEseCYAfupY62+Jzzr0adn1zJUI+RpA= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=r0LJE/sP; arc=fail smtp.client-ip=52.101.101.91 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="r0LJE/sP" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=Alr/hK1h6g2PtvELlUbZKPdzfioJeUUMO5DM6xDnfgMvTXM1P0FXenAhbXm4QTI04cjwZzrgnOcgCWbA3j15j3SMXpYxgap2gadWmqbe1N7dAT2W0WLRPbjfr2Ec0pnMaw4bRqaheXndTr/AdB4nilYnug4RPWzE1alGqrfuCt26aqVBs89Gwtx97avAIoreHg9Q64THaXkvLxqmeg0QzFZde5ADAalctzLG5ks/4LpuFpdNVsA1lIsln9e6dWUduMM5fj3Kxw+UGTB5eIay/ATmuc5c30tdf4F5fufs10tUywvMBZBAZU1ic1o9A+zla6wlyK+1C7x8jwqWGqR7Fw== 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=ls5pYn8rm5lbzthj1k1q3/K3MbTAy/rku+GhqFU8EJE=; b=k/zDdjMAyflcwyYGTrX+Y2iwzXg7gXXsdYpndUSDHlUxqqCb8oJaCT1f6Ksb0YWnife2Nj6F36JfOb01CuGVO7SAPvr3esysaL9zUgKQAhWPezKG74t8RPzu+WkqgtSsR7BM7OZDE//QxdS/rb2LbMxLzx7ky5ipW7OGe9mqVNnECGlYPBpn0JQDpsRmGZBgyB9h3GBouOkwtHqLw/j/x9fTLXBqXsmba27vB2MIPpG6ViWTwNSURpTLGR+ygPNCd8b35PRzve3m64YtJKTsYE/dgTSI05N4tcdn3k0xAtfggH6r+lWO/k6KhZX8JEDSRAgBG2gL1kJP+N93OMWG8g== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=ls5pYn8rm5lbzthj1k1q3/K3MbTAy/rku+GhqFU8EJE=; b=r0LJE/sPcrS2DWUFE/oB50pGB+yKdv+Z+2MVLcZZnKvki/QdzI+vhu0foMvf8aqgEiF8LEQz/f1c5oaiOMdD52N3o3eCkgjtb3LfYqRvPxKolmLo1VH5CBrJUGyu0sBy16JLSTR88SOLqKGME4DOo7kkzXUK91aWqXWJrATAqxw= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO2P265MB3263.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:156::7) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.13; Thu, 11 Jun 2026 16:28:33 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:33 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:21 +0100 Subject: [PATCH v4 19/20] rust: io: add copying methods Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-19-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195302; l=14709; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=4mlyjPbdnE6Ty78c6hzqGp3ZT8XiEp/nXwOWY38ZETc=; b=KR/3tNOa7Ka/uJ5/jypLk8ROUXznGYOrF+8ryesz8reZzvfx/z53RdpjxAO/Wn+UFW6JRCRnD REgcogNsAeMDrajuHLr3Hh6AmKq7+3dS8a2ShwXnn06L4qrGraN4tyo X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO2P265MB3263:EE_ X-MS-Office365-Filtering-Correlation-Id: f15b4f6b-9a3e-48be-148d-08dec7d67b34 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|10070799003|1800799024|7416014|376014|366016|23010399003|18002099003|22082099003|921020|3023799007|5023799004|6133799003|56012099006; X-Microsoft-Antispam-Message-Info: 54LNM4DXH0vqdYEPt5BteK27YoLAmFEKs5EoaZi++mMxG1p3/J92cXq+e1SRTwhE8yqi02uKGLOrHEAWcl1bbn2Q3Ygrfbm9A9RurVLayb0pybLvT4xp5UHyI8/PZS829LliCrNdxCwm0Fau5IZPTpqN+DTDYMB+KVTTqmuOmTPvpjorh0SbkNzpW5mqDuYelJ9z5Hb7X3j6g61FeZKxl4rgCUUgBfS1l2epo4Sqb4HolDM4rWwNUf0giUYIqM/iKbe4lJkA+k0C5NlxH3A9QVGGmWG55/Ip1wfWyailhLHKnNoURvwEbacDWNqv6XItJmStdSRM1zbMV5OR7CmpYOy1bpShPIhjqRVwxfuurD+2SL2Fg25q0HBqYSRh6IH3au6HookThdmpD+DKZCBKKVxwQEFeIwnESmfoEFqmG+UmZodsv5qZhauZ+LeqB/0GOtuz6M9fdy/FCbhKAjqfWkHwBDOsovNYp8vjZ5UddkbZjoZLZIPimaBGxLoM9HvG6ol3oUdbJ4oCzgV/uMJO0Y641X1c/gGBXjzFpn8SM+Ba9PdoI6TnUGoX+/TExnw+89KtIKHHG0kPdPT09DzlB9/FOobWZe42hcH5VlZWS+F/Z04/wvu5TfwNY+Y37Oz/hi7gMM5XagiL/Dgr5rVNWnqIDv/HrDagR9io7JrBL31krTg40EcAI67AD20UKeZb5w9oK61mVenwF56jM750CUz15aGayKhwTjoRaIQpDVA= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(10070799003)(1800799024)(7416014)(376014)(366016)(23010399003)(18002099003)(22082099003)(921020)(3023799007)(5023799004)(6133799003)(56012099006);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?VDE3TG50bG95VUVvU1pra3U5RzdJam1hc1pDcDVrcCt4M2k1aEUrSW8rdnpo?= =?utf-8?B?TXFmYzFZRHlLakZuWXB0Vll1bUI4QS8yZlNFRnBGYlJBT2ZYeG9iaGk0cjJP?= =?utf-8?B?VWFzWVBXdDFTT2tHSWRnTHJzWWdwbkttK2hLVERaV1dOanprd3pPcDJSUHFa?= =?utf-8?B?MGJFTGYzZVoyYWdJRDV5Q1BTK2s1ZW9OV1hKTXlOZklKdUZNNFFwWDduTjdv?= =?utf-8?B?NThmUWdKNXhqVjlDZGRqalhtb2tuc0pJU29IUXlGcHZMRmhPQ2pLZXlId1hx?= =?utf-8?B?Umk3S0NQZ1dQSE9Cc1U4a0srOVNrdWNGdys5bDBpbDREZUplbEpselhaZU13?= =?utf-8?B?UnJ2elFyc3RFM2YwMzBrYWRCT3NKeXFOcTQ0aVBYYlQ3emt1SDFzR09jZ1hP?= =?utf-8?B?MHZtQkdEQkJRdFN1Lzg0akpxT2F6WW1vL1ZadW93ckRiUS9PVTZlZS9Uc0M0?= =?utf-8?B?clRJcTE1d0wxQlFTeWpkWUo0NmtVL3Rqc2l1ZHhpUUZpREFwOGdDcWFzRVZ6?= =?utf-8?B?R1I5eE9XRDEyWEppUFRMeWNTdERBSk9oY0NaaHpqNUZVMjl6d2hMd05mQlRw?= =?utf-8?B?RkFPVHByL2YrOXBuMmx5NlEyUml2MndIeUJQaGNkTExuNDlSNEhWbE94MmNT?= =?utf-8?B?Q2tLYTcyRXdLUmNOeVNCLzZWaGpGMDNMcmhyQm44bjlzdzBPMUl5Z2RWWXYv?= =?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ELzM5Snp3YlBDQjY1VE9O?= =?utf-8?B?cTdJR3JGWit6eTFHT0Rjd3E5clZyUitKZTRHMnE4YnAzUDFFbms2RHY5UXVq?= =?utf-8?B?U1NtclJiYnliT1V1dTZ6VTYrMU14ZWUrYkNRbENFcTVQdTFTL2JyNzJKZG1F?= =?utf-8?B?QnNSc3owNnorcSthNTc2NVZqV3J1N2xrYjl4NWxDWHk0ZGJ1b3h2TytKUEJU?= =?utf-8?B?Z3pBRGJVVjI3enFXTkNhTU9mZmpxNWNMWTRZci9vaGhtSGRLWlcyYnl5dGds?= =?utf-8?B?K01VdnJBQUZwMTVldEgyQ2Q5QVMzdVljN0JXV3VReUh1cDU5TTFvMFRsN1Zy?= =?utf-8?B?SEpTOVd0RHArM2VhSDdQNjU2MWY5Uk5jNkxzRktrOWhmdXZXM0dkUzVvVDdR?= =?utf-8?B?WFZHM0xDaFpjOXhucGM2aExlOHlHejNyS29NMkpHMW8rNUdObCtLZU5Xbks1?= =?utf-8?B?Sk5ydC9PQk5MV2VJclZhcFNlYnozVndReTVlUEhQdnFEKzV6OWtpZmZ2WW9U?= =?utf-8?B?WnJFRWc3OEdtSjBFOGF5ZEoyRlNVQ2gwNEpxYjlHZ2g4QWFPS2NVVWMxYldn?= =?utf-8?B?N2Zac0tsN2l3cmxhY1g3b2tRVHNzclBuL3g2bmVsaUZJU3V6NFdXakFsWmxZ?= =?utf-8?B?ak82R05zenBFSXpLSzR4UW9RZGQ4c1pTbkJZQWhFRmpLSDhoMGNyUDFjU2Q5?= =?utf-8?B?QXhRS2s5Vy9QemloSGozWk55WnBhbkh2MnN3TWQrRnk0UmNoRUViQT09?= X-OriginatorOrg: garyguo.net X-MS-Exchange-CrossTenant-Network-Message-Id: f15b4f6b-9a3e-48be-148d-08dec7d67b34 X-MS-Exchange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:33.8044 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: Vi0j7krBLBhirHsUFhhXqKqLkOhAgB0swwg2Jtb3+E7oqw25iy4Ej3XxM61ti0H7p9d8qQNkWCv6+yH0Lq2nGQ== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO2P265MB3263 One feature that was lost from the old `dma_read!` and `dma_write!` when moving to `io_read!` and `io_write!` was the ability to read/write a large structs. However, the semantics was unclear to begin with, as there was no guarantee about their atomicity even for structs that were small enough to fit in u32. Re-introduce the capability in the form of copying methods. dma_read!(foo, bar) -> io_project!(foo, bar).copy_read() dma_write!(foo, bar, baz) -> io_project!(foo, bar).copy_write(baz) Model these semantics after memcpy so user has clear expectation of lack of atomicity. As an additional benefit of this change, this now works for MMIO as well by mapping them to `memcpy_{from,to}io`. For slices which is DST so the `copy_read` and `copy_write` API above can't work, add `copy_from_slice` and `copy_to_slice` to copy from/to normal memory. Signed-off-by: Gary Guo Suggested-by: Danilo Krummrich --- rust/helpers/io.c | 13 +++ rust/kernel/dma.rs | 25 +++++ rust/kernel/io.rs | 238 +++++++++++++++++++++++++++++++++++++++++++= +++- samples/rust/rust_dma.rs | 15 ++- 4 files changed, 285 insertions(+), 6 deletions(-) diff --git a/rust/helpers/io.c b/rust/helpers/io.c index 397810864a24..7ed9a4f77f1b 100644 --- a/rust/helpers/io.c +++ b/rust/helpers/io.c @@ -19,6 +19,19 @@ __rust_helper void rust_helper_iounmap(void __iomem *add= r) iounmap(addr); } =20 +__rust_helper void rust_helper_memcpy_fromio(void *dst, + const volatile void __iomem *src, + size_t count) +{ + memcpy_fromio(dst, src, count); +} + +__rust_helper void rust_helper_memcpy_toio(volatile void __iomem *dst, + const void *src, size_t count) +{ + memcpy_toio(dst, src, count); +} + __rust_helper u8 rust_helper_readb(const void __iomem *addr) { return readb(addr); diff --git a/rust/kernel/dma.rs b/rust/kernel/dma.rs index 0ff4cce8e809..37bc20895803 100644 --- a/rust/kernel/dma.rs +++ b/rust/kernel/dma.rs @@ -18,6 +18,7 @@ IoBackend, IoBase, IoCapable, + IoCopyable, SysMem, SysMemBackend, // }, @@ -1196,6 +1197,30 @@ fn io_write<'a>(view: Self::View<'a, T>, value: T) { } } =20 +impl IoCopyable for CoherentBackend { + #[inline] + unsafe fn copy_from_io(view: Self::View<'_, [u8]>, buffer: *mut u8) { + // SAFETY: Per safety requirement. + unsafe { SysMemBackend::copy_from_io(view.cpu_addr, buffer) } + } + + #[inline] + unsafe fn copy_to_io(view: Self::View<'_, [u8]>, buffer: *const u8) { + // SAFETY: Per safety requirement. + unsafe { SysMemBackend::copy_to_io(view.cpu_addr, buffer) } + } + + #[inline] + fn copy_read(view: Self::View<'_, T>) -> T { + SysMemBackend::copy_read(view.cpu_addr) + } + + #[inline] + fn copy_write(view: Self::View<'_, T>, value: = T) { + SysMemBackend::copy_write(view.cpu_addr, value) + } +} + impl<'a, T: ?Sized + KnownSize> IoBase<'a> for CoherentView<'a, T> { type Backend =3D CoherentBackend; type Target =3D T; diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index f64ca2202ff2..16f818d396bf 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -5,7 +5,8 @@ //! C header: [`include/asm-generic/io.h`](srctree/include/asm-generic/io.= h) =20 use core::{ - marker::PhantomData, // + marker::PhantomData, + mem::MaybeUninit, // }; =20 use crate::{ @@ -227,6 +228,61 @@ pub trait IoCapable: IoBackend { fn io_write<'a>(view: Self::View<'a, T>, value: T); } =20 +/// Trait indicating that an I/O backend supports memory copy operations. +pub trait IoCopyable: IoBackend { + /// Copy contents of `view` to `buffer`. + /// + /// # Safety + /// + /// - `buffer` is valid for volatile write for `view.size()` bytes. + unsafe fn copy_from_io(view: Self::View<'_, [u8]>, buffer: *mut u8); + + /// Copy `size` bytes from `buffer` to `address`. + /// + /// # Safety + /// + /// - `buffer` is valid for volatile read for `view.size()` bytes. + unsafe fn copy_to_io(view: Self::View<'_, [u8]>, buffer: *const u8); + + /// Copy from `view` and return the value. + #[inline] + fn copy_read(view: Self::View<'_, T>) -> T { + // Project `self` to `[u8]`. + let ptr =3D Self::as_ptr(view); + // SAFETY: This is a identity projection. + let slice_view =3D unsafe { + Self::project_view( + view, + core::ptr::slice_from_raw_parts_mut::(ptr.cast(), size= _of::()), + ) + }; + + let mut buf =3D MaybeUninit::::uninit(); + // SAFETY: `buf.as_mut_ptr()` is valid for write for `size_of::= ()` bytes. + unsafe { Self::copy_from_io(slice_view, buf.as_mut_ptr().cast()) }; + // SAFETY: T: FromBytes` guarantee that all bit patterns are valid. + unsafe { buf.assume_init() } + } + + /// Copy `value` to `view`. + #[inline] + fn copy_write(view: Self::View<'_, T>, value: T) { + // Project `self` to `[u8]`. + let ptr =3D Self::as_ptr(view); + // SAFETY: This is a identity projection. + let slice_view =3D unsafe { + Self::project_view( + view, + core::ptr::slice_from_raw_parts_mut::(ptr.cast(), size= _of::()), + ) + }; + + // SAFETY: `&raw const value` is valid for read for `size_of::(= )` bytes. + unsafe { Self::copy_to_io(slice_view, (&raw const value).cast()) }; + core::mem::forget(value); + } +} + /// Describes a given I/O location: its offset, width, and type to convert= the raw value from and /// into. /// @@ -304,6 +360,24 @@ fn size(self) -> usize { KnownSize::size(Self::Backend::as_ptr(self.as_view())) } =20 + /// Returns the length of the slice in number of elements. + #[inline] + fn len(self) -> usize + where + Self: Io<'a, Target =3D [T]>, + { + Self::Backend::as_ptr(self.as_view()).len() + } + + /// Returns `true` if the slice has a length of 0. + #[inline] + fn is_empty(self) -> bool + where + Self: Io<'a, Target =3D [T]>, + { + self.len() =3D=3D 0 + } + /// Try to convert into a different typed I/O view. /// /// The target type must be of same or smaller size to current type, a= nd the current view must @@ -391,6 +465,105 @@ fn write_val(self, value: Self::Target) Self::Backend::io_write(self.as_view(), value) } =20 + /// Copy-read from I/O memory. + /// + /// There is no atomicity guarantee. + /// + /// # Examples + /// + /// ```no_run + /// # use kernel::io::*; + /// # fn test_copy_read(mmio: Mmio<'_, [u8; 6]>) { + /// // let mmio: Mmio<'_, [u8; 6]>; + /// let val: [u8; 6] =3D mmio.copy_read(); + /// # } + /// ``` + #[inline] + fn copy_read(self) -> Self::Target + where + Self::Backend: IoCopyable, + Self::Target: Sized + FromBytes, + { + Self::Backend::copy_read(self.as_view()) + } + + /// Copy-write to I/O memory. + /// + /// There is no atomicity guarantee. + /// + /// # Examples + /// + /// ```no_run + /// # use kernel::io::*; + /// # fn test_copy_write(mmio: Mmio<'_, [u8; 6]>) { + /// // let mmio: Mmio<'_, [u8; 6]>; + /// mmio.copy_write([0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]); + /// # } + /// ``` + #[inline] + fn copy_write(self, value: Self::Target) + where + Self::Backend: IoCopyable, + Self::Target: Sized + IntoBytes, + { + Self::Backend::copy_write(self.as_view(), value); + } + + /// Copy bytes from slice to I/O memory. + /// + /// The length of `self` must be the same as `data`, similar to [`[u8]= ::copy_from_slice`]. + /// + /// # Examples + /// + /// ```no_run + /// # use kernel::io::*; + /// # fn test_copy_write(mmio: Mmio<'_, [u8]>) { + /// // let mmio: Mmio<'_, [u8]>; + /// mmio.copy_from_slice(&[0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]); + /// # } + /// ``` + #[inline] + fn copy_from_slice(self, data: &[u8]) + where + Self::Backend: IoCopyable, + Self: Io<'a, Target =3D [u8]>, + { + assert_eq!(self.len(), data.len()); + + // SAFETY: `data.as_ptr()` is valid for read for `self.size()` byt= es. + unsafe { + Self::Backend::copy_to_io(self.as_view(), data.as_ptr()); + } + } + + /// Copy bytes from I/O memory to slice. + /// + /// The length of `self` must be the same as `data`, similar to [`[u8]= ::copy_from_slice`]. + /// + /// # Examples + /// + /// ```no_run + /// # use kernel::io::*; + /// # fn test_copy_write(mmio: Mmio<'_, [u8]>) { + /// // let mmio: Mmio<'_, [u8]>; + /// let mut buf =3D [0; 6]; + /// mmio.copy_to_slice(&mut buf); + /// # } + /// ``` + #[inline] + fn copy_to_slice(self, data: &mut [u8]) + where + Self::Backend: IoCopyable, + Self: Io<'a, Target =3D [u8]>, + { + assert_eq!(self.len(), data.len()); + + // SAFETY: `data.as_ptr()` is valid for write for `self.size()` by= tes. + unsafe { + Self::Backend::copy_from_io(self.as_view(), data.as_mut_ptr()); + } + } + /// Returns a view for a given `offset`, performing compile-time bound= checks. // Always inline to optimize out error path of `build_assert`. #[inline(always)] @@ -981,6 +1154,28 @@ fn io_write(view: <$backend as IoBackend>::View<'_, $= ty>, value: $ty) { #[cfg(CONFIG_64BIT)] impl_mmio_io_capable!(MmioBackend, u64, readq, writeq); =20 +impl IoCopyable for MmioBackend { + #[inline] + unsafe fn copy_from_io(view: Self::View<'_, [u8]>, buffer: *mut u8) { + // SAFETY: + // - `view.ptr` is valid MMIO memory for `view.size()` bytes. + // - `buffer` is valid for write for `view.size()` bytes. + unsafe { + bindings::memcpy_fromio(buffer.cast(), view.ptr.cast(), view.s= ize()); + } + } + + #[inline] + unsafe fn copy_to_io(view: Self::View<'_, [u8]>, buffer: *const u8) { + // SAFETY: + // - `view.ptr` is valid MMIO memory for `view.size()` bytes. + // - `buffer` is valid for read for `view.size()` bytes. + unsafe { + bindings::memcpy_toio(view.ptr.cast(), buffer.cast(), view.siz= e()); + } + } +} + /// [`Mmio`] but using relaxed accessors. /// /// This type provides an implementation of [`Io`] that uses relaxed I/O M= MIO operands instead of @@ -1145,6 +1340,47 @@ fn io_write(view: SysMem<'_, $ty>, value: $ty) { #[cfg(CONFIG_64BIT)] impl_sysmem_io_capable!(u64); =20 +impl IoCopyable for SysMemBackend { + #[inline] + unsafe fn copy_from_io(view: Self::View<'_, [u8]>, buffer: *mut u8) { + // Use `bindings::memcpy` instead of copy_nonoverlapping for volat= ile. + // SAFETY: + // - `view.ptr` is in CPU address space and valid for read. + // - `buffer` is valid for write for `view.size()` bytes which is = equal to `view.ptr.len()`. + unsafe { bindings::memcpy(buffer.cast(), view.ptr.cast(), view.ptr= .len()) }; + } + + #[inline] + unsafe fn copy_to_io(view: Self::View<'_, [u8]>, buffer: *const u8) { + // Use `bindings::memcpy` instead of copy_nonoverlapping for volat= ile. + // SAFETY: + // - `view.ptr` is in CPU address space and valid for write. + // - `buffer` is valid for read for `view.size()` bytes which is e= qual to `view.ptr.len()`. + unsafe { bindings::memcpy(view.ptr.cast(), buffer.cast(), view.ptr= .len()) }; + } + + #[inline] + fn copy_read(view: Self::View<'_, T>) -> T { + // SAFETY: + // - Per type invariant, `ptr` is valid and aligned. + // - Using read_volatile() here so that race with hardware is well= -defined. + // - Using read_volatile() here is not sound if it races with othe= r CPU per Rust + // rules, but this is allowed per LKMM. + // - The macro is only used on primitives so all bit patterns are = valid. + unsafe { view.ptr.read_volatile() } + } + + #[inline] + fn copy_write(view: Self::View<'_, T>, value: T) { + // SAFETY: + // - Per type invariant, `ptr` is valid and aligned. + // - Using write_volatile() here so that race with hardware is wel= l-defined. + // - Using write_volatile() here is not sound if it races with oth= er CPU per Rust + // rules, but this is allowed per LKMM. + unsafe { view.ptr.write_volatile(value) } + } +} + /// System memory region. /// /// Provides `Io` trait implementation for kernel virtual address ranges, diff --git a/samples/rust/rust_dma.rs b/samples/rust/rust_dma.rs index 6727c441658a..b629acc6d915 100644 --- a/samples/rust/rust_dma.rs +++ b/samples/rust/rust_dma.rs @@ -12,7 +12,11 @@ Device, DmaMask, // }, - io::io_read, + io::{ + io_project, + io_read, + Io, // + }, page, pci, prelude::*, scatterlist::{Owned, SGTable}, @@ -35,6 +39,7 @@ struct DmaSampleDriver { (0xcd, 0xef), ]; =20 +#[derive(FromBytes, IntoBytes)] struct MyStruct { h: u32, b: u32, @@ -74,11 +79,11 @@ fn probe<'bound>( // SAFETY: There are no concurrent calls to DMA allocation and= mapping primitives. unsafe { pdev.dma_set_mask_and_coherent(mask)? }; =20 - let mut ca: CoherentBox<[MyStruct]> =3D - CoherentBox::zeroed_slice(pdev.as_ref(), TEST_VALUES.len()= , GFP_KERNEL)?; + let ca: Coherent<[MyStruct]> =3D + Coherent::zeroed_slice(pdev.as_ref(), TEST_VALUES.len(), G= FP_KERNEL)?; =20 for (i, value) in TEST_VALUES.into_iter().enumerate() { - ca.init_at(i, MyStruct::new(value.0, value.1))?; + io_project!(ca, [panic: i]).copy_write(MyStruct::new(value= .0, value.1)); } =20 let size =3D 4 * page::PAGE_SIZE; @@ -88,7 +93,7 @@ fn probe<'bound>( =20 Ok(try_pin_init!(Self { pdev: pdev.into(), - ca: ca.into(), + ca, sgt <- sgt, })) }) --=20 2.54.0 From nobody Wed Jun 17 01:38:28 2026 Received: from LO0P265CU003.outbound.protection.outlook.com (mail-uksouthazon11022092.outbound.protection.outlook.com [52.101.96.92]) (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 AD26A47CC81; Thu, 11 Jun 2026 16:28:42 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.96.92 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195324; cv=fail; b=cUE61TGEghyQlj9Chf8orORGVW/AEozv+VP8Jk+Jr8mzRTZ9AVMFNhJ5KeXnP7a3qq+bB8zB8aTTllZE0wkfH/7DlybA61/95+Oci9C00T6/swUDl0vEm+MsYByzl5PvmY25QHNKgHEv9FYMnrGILyD6G3ewP9Hn6znvFXE98Zs= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1781195324; c=relaxed/simple; bh=AGvF2/hSGFWEibxHYJRZxGGpo9SaGA+vZSfD5GYxu6o=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=QzTfbBiRFUcTLY/ecfeTVjQe9Lv+VZvpQb5xhYSOP9OCiIDb+90xBnh0OQoNCI0E87baYqQa7EnmmlqUGwNKACYM4eBWlw6RM9rh3W2Hp3xWfcD7LFolm0Tf4lHgeI0RzNvkwBHZnEw+re78XlVgIKF5yC6kuDTT3EP4NRSSGIY= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net; spf=pass smtp.mailfrom=garyguo.net; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b=OMRC8Isb; arc=fail smtp.client-ip=52.101.96.92 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=garyguo.net Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=garyguo.net Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=garyguo.net header.i=@garyguo.net header.b="OMRC8Isb" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=X6dD0pHV9dmWJwgLv4mvZCFVWu5TY2MJUjocD/7bEE2gNLcnX+NGi5SV8D/wS/1mDqX3Web2bhz6Snc5P2fRxeNMCrwn3V1C41Umhz+hgbMmvPxNXAotT6A2VzMczc5FG6JeN4IE41Jrlg1GFQylSmLP8NEth4VSvdiL5BqzN95KQLCTT5l+nrY3b9MyM9BZojv305jsy18o7VoRMQ/Q+Z2fnYxYLyt2iMaH++phIj53J8oYbQND8tWRucJ91dLXQq9BuoWsP6DdPXcBm1+Q80dJsOYrLvUcC2K9b3+cb92fNKtwVy950y09NQpIIc0yZWkIcFN6uuJPrcZQP22yyQ== 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=OPmicdJDeHPwAA+5x7f6CCnvjBWluXEwiR4ROiYGTW4=; b=RRmcnZNIb5a8+AyN9BvjbG+ZF0MibOPjg+ux4cX/6Gk0vWrYR/on/w+OMa45OwDmvqT3o5fzBRWi6jbU2sTzh3Mi2S82woyAc4fC4vJmcm30pnUBMVi5uLWFm7roPhvk587xuo4pvtk0KuwY0wtzSZEJu0JFG5IptXk17qOO3ute4X4cP3ogabf9jdiAju7VbxFmuMwr1hpj2a7fcVqkFVWKGAlsRHzELFy7EobAShhNTVxVrNi2B98jdfaTeqKtnr+dxi21p2AQzpORGNqLP0bfA60ZtJiApna+o0uqOdcPyAz26UXwUbcHQKQiWAkgrs878fh2pTAP77bcmSSEfw== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=garyguo.net; dmarc=pass action=none header.from=garyguo.net; dkim=pass header.d=garyguo.net; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=garyguo.net; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=OPmicdJDeHPwAA+5x7f6CCnvjBWluXEwiR4ROiYGTW4=; b=OMRC8IsbhfFmGzyPd23zI4NO3+dZY0/DYoDrdJCRrMh7sUPRXnxRjZPs0gKCCz/1pl6VdCaLicyOfpEFSIKStWyXPVGQFQhIlOQDGk/2tGTPTN9ef3UE0vSX6dH8bmMHn/GAs/WCQP9Rw/lSpt47Cwm+PFqUl5NS70pOqvIywDo= Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=garyguo.net; Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) by LO2P265MB3263.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:156::7) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.21.113.13; Thu, 11 Jun 2026 16:28:34 +0000 Received: from CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995]) by CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM ([fe80::6c9e:93c8:10db:e995%6]) with mapi id 15.21.0113.011; Thu, 11 Jun 2026 16:28:34 +0000 From: Gary Guo Date: Thu, 11 Jun 2026 17:28:22 +0100 Subject: [PATCH v4 20/20] rust: io: implement `IoSysMap` Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20260611-io_projection-v4-20-1f7224b02dcb@garyguo.net> References: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> In-Reply-To: <20260611-io_projection-v4-0-1f7224b02dcb@garyguo.net> To: Alice Ryhl , Daniel Almeida , Greg Kroah-Hartman , "Rafael J. Wysocki" , Miguel Ojeda , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Abdiel Janulgue , Robin Murphy , Alexandre Courbot , David Airlie , Simona Vetter Cc: Danilo Krummrich , driver-core@lists.linux.dev, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-pci@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org X-Mailer: b4 0.15.2 X-Developer-Signature: v=1; a=ed25519-sha256; t=1781195302; l=5479; i=gary@garyguo.net; s=20221204; h=from:subject:message-id; bh=AGvF2/hSGFWEibxHYJRZxGGpo9SaGA+vZSfD5GYxu6o=; b=bbZr8M7GrKpU1CS/yIgftjgU+co0rixsTFvsPYIgZRfiQRIyhe0ayexpgbqP6gK0Z+Y/GGbnL UE3PvMcpg0oDu+YwGx1HcMyAYtzo71lDv+sTkHVkrW0ierL9jRwzuC7 X-Developer-Key: i=gary@garyguo.net; a=ed25519; pk=vB3uIX95SM4eVrIqo1DWNWKDKD2xzB+yLLLr0yOPYMo= X-ClientProxiedBy: LO6P265CA0015.GBRP265.PROD.OUTLOOK.COM (2603:10a6:600:339::8) To CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM (2603:10a6:400:27c::13) 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: CW1P265MB8877:EE_|LO2P265MB3263:EE_ X-MS-Office365-Filtering-Correlation-Id: bc9c7400-846f-4c4c-7ed2-08dec7d67b8f X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|10070799003|1800799024|7416014|376014|366016|23010399003|18002099003|22082099003|921020|5023799004|6133799003|56012099006; X-Microsoft-Antispam-Message-Info: PA1c5wlNR4F/7fecPliMjCBW6WXfS+4Rg8/SxCsUw3gePn0znJNSqWZqo5p07uDi8QNQO68P6QkfBXdwKz9x6jLckSP2olRIt25D+SIUCQycjj6UI1HoZs5LZ00TRHmhc+kzNb4PA5Z3WPqUaocDGCCqr7pbEWHem9o95DuVs0TM6ncwIjvKRASp6CBp98v8fxq+3Mk4R1S9t6jGKakQ1eiqhDUBv0iNrxuDGz62DTiZPmWyeJdqLty2yyqjlNuwPv8PgaC7qG1ZiRZGPo64f1sSSiKlAvcdc1T833Mv+mZ0MT4A01viM0C58rOamDIPcusn2K0h7zY0p7mDVGImhbYZfsfb04hYHxtZslT5RKPySwFAgnsijoXMFhIQMkhSWFSz9N42IBZrYqik4sxSd1hhDSprGI6ige2dC6txhjjzP7Ub+dYcrht/9DfVp9VuiwwDSM9xLtZBG76igZ2szTpAmsZ2hYEVoTVYmWpm2YbTgQHAUet2Q4FDvXPymAQMZMCQY2iVcvzz6yFXdy+/OarCj4IzgC2skWOifUiRYyESYa0rDii1GwVmnWdoJPy9cQCLQD3NO28SdNdJTm+fnP0TPVgfh4m6tOBJtAE18PgPHscheI/ZTAD+I5tXfUekMy53cCMRUeWFMqHbuSDf83SsrDXpS14KaLVcRRNjjIosE2ulhDEnsRpEXXHlh4FVnDfiEeD0oO0MXPito2xd/5NsBg/Bu2O4h9tadsoDDIg= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM;PTR:;CAT:NONE;SFS:(13230040)(10070799003)(1800799024)(7416014)(376014)(366016)(23010399003)(18002099003)(22082099003)(921020)(5023799004)(6133799003)(56012099006);DIR:OUT;SFP:1102; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?TDlMNG1GUGpnbDhad2NSU0t3ZEljRmtRVzA5YzJTV1ROQzVndW1aZ29ITU52?= =?utf-8?B?RXVOUy81RVcyYVNQK1BUbVMxZXpSOUs4cDJQNTlIcjZXbkdmQWlYbWhaek1U?= =?utf-8?B?YUJxNDRpL1BEdWlKTDh2ZEtrcHFGcFJLKzNXazc4UloyTFUxZG1wMVJOQTF3?= =?utf-8?B?UE1wYVQzZHUycHAzRWxyVWl4OWFnYUU2MWpocEkvU1JJWGJJSkd0M2w5L3M5?= =?utf-8?B?QU9taVRMNGVmZE9ZalNaSFJ1Yk41M0tVRFNDTnMrRThWaCtibFVmNXZWL2JD?= =?utf-8?B?OEFYV1NGRWhXOEZUVmd6WkZyc2J6bm5HVlowQnlQNDh2TkdaanpKVW5HTGRw?= =?utf-8?B?Y2xRSkJKRXFPVUhiTitIaDFXamUvL1FRVm8vbXZEVVNEWXVOUmtJRDJxTzlW?= =?utf-8?B?ZWlCdVRFckNXZ09xaHE1dTJMMWxHSXh0eE05eWtCUmErL1NZUmR2a1Z6ZDcz?= =?utf-8?B?UTVnTFJZNDJsUXkzcTFST0dSUjFoVkc5ZUpNbGVaYVh6RmluN29EL2RQaUVx?= =?utf-8?B?d0RqV3dMbjdxQUR4RGNlTTlLVVpRUlpFcndKWU14aVU5R0ZXOUNpTEdXZWdt?= =?utf-8?B?NzFzS0syUjNMUlRucGw4QnZwOCtSUFhaWnZP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GM0tTZnpMVFdIQjVGdDRJZ1lUc0pHcGdBQzJkYmVjWlRy?= =?utf-8?B?bUhLbmRNdENrcFZMMmtCVEpHbGJlWHBpSFVJTzloSW9Nbk1aRDlYSEVoODdl?= =?utf-8?B?R3RveURiVjJYZUdFMyswYm8rY1FRQmRLSXdpNFpiaWtKeHB3b29CeXNyVWZF?= =?utf-8?B?OEw5RERyNUpDOXVielIwSTFnMXZnNjRtVEtMaTN0a0N5S0I3OEoxTkJUemZT?= =?utf-8?B?VVNGclZDb09pK3RwRDI0bUhKb3g4U1lEVlRVclMxUldzZnd3ck9DT0FUWjQ1?= =?utf-8?B?Zk5MVTV0Ky9NRllJRzhDYWFzcGxBUG83R21Id3hIbTFWTFpZbXdiVVU1MW41?= =?utf-8?B?YnBDVWhnQXRDQ0NVa1RtNmttaEFvU09DbW5PSE5XSGhXZGFMNWZNOTRRYTdk?= =?utf-8?B?WUtOU0VwVVVVei9Pam1aL0FOc0N4MWNIbnlETThBUkRFdTlTR2YrODBzdlJp?= =?utf-8?B?ZURjUzk4U0Framc2NVMrbEtIaTdZSTdqN2hyWUV4ZVI0aXFzak9yRkJpRlF1?= =?utf-8?B?MG5UT3lzam9SWFZZZnk2ekNOY2RsSE9zbkh6eXdPYk4rU0hkeFVvV2hZYjdP?= =?utf-8?B?S2l2TVoxcHNlUkpvUmpvUUFPSUt0NWF2MzMrT3dPNUhCY0FucURRYzdpdEwv?= =?utf-8?B?ZmhLL1JJZkpYTDBQYWlwUUphMG90NVA4V0JQU0tMeUxWYkw2NTRleENROU1C?= =?utf-8?B?Q1FDanYrbW5oN3NFMzhHS1Q4UGxMNHVzckxQcHNBRTZFdXZ6WmU3Q20za2h2?= =?utf-8?B?dFBZTlV5WUU1dXNiYjArU1F5RXR5TisyeTAxcGNxaG9kK21lMCtOZz09?= X-OriginatorOrg: garyguo.net X-MS-Exchange-CrossTenant-Network-Message-Id: bc9c7400-846f-4c4c-7ed2-08dec7d67b8f X-MS-Exchange-CrossTenant-AuthSource: CW1P265MB8877.GBRP265.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 11 Jun 2026 16:28:34.3938 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: bbc898ad-b10f-4e10-8552-d9377b823d45 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: WNvZtOkkI0CSnlKy68g/hwiMK++9aoMVnuvhtXyIMSv2zZmqDvhh459Ob18MZRKdkaQFqY3Ol9GXTDISNyC5EQ== X-MS-Exchange-Transport-CrossTenantHeadersStamped: LO2P265MB3263 Add an enum as sum type for `Mmio` and `SysMem`. This serves similar purpose of `iosys_map`. Thanks to Rust's type system, all of projection and struct read/write can be handled by the generic I/O projection mechanism (i.e. `io_project!`, `io_read!, `io_write!`) for free, and there is no need to provide things like `iosys_map_rd_field` or `iosys_map_wr_field`. An enum type also makes it very easy to construct or destruct. This could be made more generic by implementing on a general purpose sum type like `Either`; however this is kept specific unless a need arises that warrants this to be generic over other I/O backends. Signed-off-by: Gary Guo Suggested-by: Danilo Krummrich --- rust/kernel/io.rs | 135 ++++++++++++++++++++++++++++++++++++++++++++++++++= ++++ 1 file changed, 135 insertions(+) diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index 16f818d396bf..5cd4756cf237 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -1443,6 +1443,141 @@ fn as_view(self) -> ::V= iew<'a, Self::Target> { } } =20 +/// I/O Backend for [`IoSysMap`]. +pub struct IoSysMapBackend; + +/// Either [`Mmio`] or [`SysMem`]. +/// +/// This can be used when a piece of logic may wish to handle both MMIO or= system memory but does +/// not want or cannot be generic over I/O backends. This serves a similar= purpose to +/// [`include/linux/iosys-map.h`] in C. +/// +/// This type can be used like any other types that implements [`Io`]; thi= s also include +/// [`io_project!`], [`io_read!`], [`io_write!`]. +/// +/// [`include/linux/iosys-map.h`](srctree/include/linux/iosys-map.h) +pub enum IoSysMap<'a, T: ?Sized> { + Io(Mmio<'a, T>), + Sys(SysMem<'a, T>), +} + +impl Copy for IoSysMap<'_, T> {} +impl Clone for IoSysMap<'_, T> { + #[inline] + fn clone(&self) -> Self { + *self + } +} + +impl<'a, T: ?Sized> From> for IoSysMap<'a, T> { + #[inline] + fn from(value: Mmio<'a, T>) -> Self { + IoSysMap::Io(value) + } +} + +impl<'a, T: ?Sized> From> for IoSysMap<'a, T> { + #[inline] + fn from(value: SysMem<'a, T>) -> Self { + IoSysMap::Sys(value) + } +} + +impl IoBackend for IoSysMapBackend { + type View<'a, T: ?Sized + KnownSize> =3D IoSysMap<'a, T>; + + #[inline] + fn as_ptr<'a, T: ?Sized + KnownSize>(view: Self::View<'a, T>) -> *mut = T { + match view { + IoSysMap::Io(l) =3D> MmioBackend::as_ptr(l), + IoSysMap::Sys(r) =3D> SysMemBackend::as_ptr(r), + } + } + + #[inline] + unsafe fn project_view<'a, T: ?Sized + KnownSize, U: ?Sized + KnownSiz= e>( + view: Self::View<'a, T>, + ptr: *mut U, + ) -> Self::View<'a, U> { + match view { + // SAFETY: Per safety requirement. + IoSysMap::Io(l) =3D> IoSysMap::Io(unsafe { MmioBackend::projec= t_view(l, ptr) }), + // SAFETY: Per safety requirement. + IoSysMap::Sys(r) =3D> IoSysMap::Sys(unsafe { SysMemBackend::pr= oject_view(r, ptr) }), + } + } +} + +impl IoCapable for IoSysMapBackend +where + MmioBackend: IoCapable, + SysMemBackend: IoCapable, +{ + #[inline] + fn io_read(view: Self::View<'_, T>) -> T { + match view { + IoSysMap::Io(l) =3D> MmioBackend::io_read(l), + IoSysMap::Sys(r) =3D> SysMemBackend::io_read(r), + } + } + + #[inline] + fn io_write<'a>(view: Self::View<'a, T>, value: T) { + match view { + IoSysMap::Io(l) =3D> MmioBackend::io_write(l, value), + IoSysMap::Sys(r) =3D> SysMemBackend::io_write(r, value), + } + } +} + +impl IoCopyable for IoSysMapBackend { + #[inline] + unsafe fn copy_from_io(view: Self::View<'_, [u8]>, buffer: *mut u8) { + match view { + // SAFETY: Per safety requirement. + IoSysMap::Io(l) =3D> unsafe { MmioBackend::copy_from_io(l, buf= fer) }, + // SAFETY: Per safety requirement. + IoSysMap::Sys(r) =3D> unsafe { SysMemBackend::copy_from_io(r, = buffer) }, + } + } + + #[inline] + unsafe fn copy_to_io(view: Self::View<'_, [u8]>, buffer: *const u8) { + match view { + // SAFETY: Per safety requirement. + IoSysMap::Io(l) =3D> unsafe { MmioBackend::copy_to_io(l, buffe= r) }, + // SAFETY: Per safety requirement. + IoSysMap::Sys(r) =3D> unsafe { SysMemBackend::copy_to_io(r, bu= ffer) }, + } + } + + #[inline] + fn copy_read(view: Self::View<'_, T>) -> T { + match view { + IoSysMap::Io(l) =3D> MmioBackend::copy_read(l), + IoSysMap::Sys(r) =3D> SysMemBackend::copy_read(r), + } + } + + #[inline] + fn copy_write(view: Self::View<'_, T>, value: T) { + match view { + IoSysMap::Io(l) =3D> MmioBackend::copy_write(l, value), + IoSysMap::Sys(r) =3D> SysMemBackend::copy_write(r, value), + } + } +} + +impl<'a, T: ?Sized + KnownSize> IoBase<'a> for IoSysMap<'a, T> { + type Backend =3D IoSysMapBackend; + type Target =3D T; + + #[inline] + fn as_view(self) -> IoSysMap<'a, T> { + self + } +} + // This helper turns associated functions to methods so it can be invoked = in macro. // Used by `io_project!()` only. #[doc(hidden)] --=20 2.54.0