From nobody Sat Feb 7 16:33:58 2026 Received: from sender4-pp-f112.zoho.com (sender4-pp-f112.zoho.com [136.143.188.112]) (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 6BB871DBB3A; Thu, 16 Jan 2025 13:06:06 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=pass smtp.client-ip=136.143.188.112 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737032769; cv=pass; b=i7MI4UgBmw159ahoyBwdYgQbtVNrrA6M0cD5NC8x2VHbFzeY9z1Iz3QdtzCrZr2gnJKNrWMGVemDwCtSK29OFfEDbMK2kerz7lwVCclZHjG6nspJHJAQo9x5S43BFwnfS3Jv2CP3hctDZ6knadqk+141rfxzMxwem+E+kQZEMSQ= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737032769; c=relaxed/simple; bh=PSU/A3EW/CGdM9iFGZ5hiABQAZI/f3/Re6CzRih2/ps=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=uv/DgjnRUtTaXYsS5sE6Y9hKBdJ34Gxgkm7F8ob9XHwgZTZ+XgUIXi7ZlEES6hplNEiFLnRg0UXvpm7/E4mdlbAjQjb0RILAKbdb8EyZqHaB9JrxDUaxnfIOQHgB8uJsRRToZ6JhCnNvikcmwQ1QSI1r9BJEn6tO5O5i7Q/nOO0= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com; spf=pass smtp.mailfrom=collabora.com; dkim=pass (1024-bit key) header.d=collabora.com header.i=daniel.almeida@collabora.com header.b=UmXR/wqm; arc=pass smtp.client-ip=136.143.188.112 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=collabora.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=collabora.com header.i=daniel.almeida@collabora.com header.b="UmXR/wqm" ARC-Seal: i=1; a=rsa-sha256; t=1737032711; cv=none; d=zohomail.com; s=zohoarc; b=DC1pxCwrixFOo2bPPVbHaoFL109Ngq5UA9tU0nZ3r248V7gINGylAfWgcVQTmBZmTGSv9HoxXPqDfD6K3TwHnKmxXQLwAPAXuIFPiNJfchgRU75gmYSSICVO/mYJuhI9t4tdgQSuZP00Mqp6HbJq6BHVVUU/JAgjmK8dhouRCWY= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1737032711; h=Content-Transfer-Encoding:Cc:Cc:Date:Date:From:From:In-Reply-To:MIME-Version:Message-ID:References:Subject:Subject:To:To:Message-Id:Reply-To; bh=tIv/wFu5hcAqXTHXWRB0ajm+LYWHFrBqdBacTD2Yu5A=; b=ExVWwch7nzMMj1b02ww0TwOjcu7z+W/2PRbWx7882R8+85c0lHY5sfnQG4ne0qb68V5MfpTh8rEc0I8A6KdN7d3vUz8ycVwXzo6ast1ZCIo+av2QRBjN7Mz+M9DZNTnUikWdL+4gDBb6ohmJyrMFfitAc7XsG9ytr0NIvNurRy0= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass header.i=collabora.com; spf=pass smtp.mailfrom=daniel.almeida@collabora.com; dmarc=pass header.from= DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; t=1737032711; s=zohomail; d=collabora.com; i=daniel.almeida@collabora.com; h=From:From:To:To:Cc:Cc:Subject:Subject:Date:Date:Message-ID:In-Reply-To:References:MIME-Version:Content-Transfer-Encoding:Message-Id:Reply-To; bh=tIv/wFu5hcAqXTHXWRB0ajm+LYWHFrBqdBacTD2Yu5A=; b=UmXR/wqmNbtGWELytcEdcJzK/YYZ/Gy7N15oAvAkVjIlwxlEZ6Fy6h7ANId6CIUc MtvgOnLgfR4GfupiuACPCEaMum3CoVvYexh1lOjWiDFA2MStgKSFbi0bm2a4Bq+XyiL UV5NV4oQLEFezoGu9jNQ8zzqapkAsL84goDBsT1s= Received: by mx.zohomail.com with SMTPS id 1737032710144449.185524274169; Thu, 16 Jan 2025 05:05:10 -0800 (PST) From: Daniel Almeida To: ojeda@kernel.org, alex.gaynor@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.mco, benno.lossin@proton.me, a.hindborg@kernel.org, aliceryhl@google.com, tmgross@umich.edu, gregkh@linuxfoundation.org, rafael@kernel.org, dakr@kernel.org, boris.brezillon@collabora.com, robh@kernel.org Cc: Daniel Almeida , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH RESEND v5 1/3] rust: io: add resource abstraction Date: Thu, 16 Jan 2025 09:56:24 -0300 Message-ID: <20250116125632.65017-2-daniel.almeida@collabora.com> X-Mailer: git-send-email 2.48.0 In-Reply-To: <20250116125632.65017-1-daniel.almeida@collabora.com> References: <20250116125632.65017-1-daniel.almeida@collabora.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-ZohoMailClient: External Content-Type: text/plain; charset="utf-8" In preparation for ioremap support, add a Rust abstraction for struct resource. A future commit will introduce the Rust API to ioremap a resource from a platform device. The current abstraction, therefore, adds only the minimum API needed to get that done. Signed-off-by: Daniel Almeida Tested-by: Christian Schrefl --- rust/bindings/bindings_helper.h | 1 + rust/helpers/io.c | 7 +++++ rust/kernel/io.rs | 2 ++ rust/kernel/io/resource.rs | 53 +++++++++++++++++++++++++++++++++ 4 files changed, 63 insertions(+) create mode 100644 rust/kernel/io/resource.rs diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index e9fdceb568b8..f9c2eedb5b9b 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/helpers/io.c b/rust/helpers/io.c index 4c2401ccd720..3cb47bd01942 100644 --- a/rust/helpers/io.c +++ b/rust/helpers/io.c @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0 =20 #include +#include =20 void __iomem *rust_helper_ioremap(phys_addr_t offset, size_t size) { @@ -99,3 +100,9 @@ void rust_helper_writeq_relaxed(u64 value, volatile void= __iomem *addr) writeq_relaxed(value, addr); } #endif + +resource_size_t rust_helper_resource_size(struct resource *res) +{ + return resource_size(res); +} + diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index d4a73e52e3ee..566d8b177e01 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -7,6 +7,8 @@ use crate::error::{code::EINVAL, Result}; use crate::{bindings, build_assert}; =20 +pub mod resource; + /// Raw representation of an MMIO region. /// /// By itself, the existence of an instance of this structure does not pro= vide any guarantees that diff --git a/rust/kernel/io/resource.rs b/rust/kernel/io/resource.rs new file mode 100644 index 000000000000..ca92f9af613b --- /dev/null +++ b/rust/kernel/io/resource.rs @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Abstraction for system resources. +//! +//! C header: [`include/linux/ioport.h`](srctree/include/linux/ioport.h) + +use crate::str::CStr; +use crate::types::Opaque; + +/// A resource abstraction. +/// +/// # Invariants +/// +/// `Resource` is a transparent wrapper around a valid `bindings::resource= `. +#[repr(transparent)] +pub struct Resource(Opaque); + +impl Resource { + /// Creates a reference to a [`Resource`] from a valid pointer. + /// + /// # Safety + /// + /// The caller must ensure that for the duration of 'a, the pointer wi= ll + /// point at a valid `bindings::resource` + /// + /// The caller must also ensure that the `Resource` is only accessed v= ia the + /// returned reference for the duration of 'a. + pub(crate) unsafe fn from_ptr<'a>(ptr: *mut bindings::resource) -> &'a= Self { + // SAFETY: Self is a transparent wrapper around `Opaque`. + unsafe { &*ptr.cast() } + } + + /// Returns the size of the resource. + pub fn size(&self) -> bindings::resource_size_t { + let inner =3D self.0.get(); + // SAFETY: safe as per the invariants of `Resource` + unsafe { bindings::resource_size(inner) } + } + + /// Returns the start address of the resource. + pub fn start(&self) -> u64 { + let inner =3D self.0.get(); + // SAFETY: safe as per the invariants of `Resource` + unsafe { *inner }.start + } + + /// Returns the name of the resource. + pub fn name(&self) -> &CStr { + let inner =3D self.0.get(); + // SAFETY: safe as per the invariants of `Resource` + unsafe { CStr::from_char_ptr((*inner).name) } + } +} --=20 2.48.0 From nobody Sat Feb 7 16:33:58 2026 Received: from sender4-pp-f112.zoho.com (sender4-pp-f112.zoho.com [136.143.188.112]) (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 942F71DBB3A; Thu, 16 Jan 2025 13:05:30 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=pass smtp.client-ip=136.143.188.112 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737032732; cv=pass; b=KCjO1RvyxR2NCQANEDL6sYE525KV8prTAIIQp83he9D75mv/AKclDczQDZhrwF7W6Ds34aUyi0HY4Km6MWjC5vqWZGeAiiICWecIzB7ODMZ+njdhB7UyG/AWMN506z/GAga/N2RJervG2/GpWrp3OQLIwM/dUKJV4GP1nzBlAeI= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737032732; c=relaxed/simple; bh=wVsYSFfTcq4Qyi8hxT3KVJPP/YjMXtye28uMP3CXwbA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=ik87epVCJ3fXDwXQzoZ9yPi7IIsTV0BLZFhGRef4eDC4JBbgS6SsLrKZVxIrFK0840/kHIYuiQkfMqzjc1YAymLyZSkn31EPv2vTFBHEeACjfUy87gy6BqYMFHVoqnAYEgIiA3uAh+HeWBRD/65ZisgfOGHrat0+XhL13JibRfg= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com; spf=pass smtp.mailfrom=collabora.com; dkim=pass (1024-bit key) header.d=collabora.com header.i=daniel.almeida@collabora.com header.b=F1vygAB2; arc=pass smtp.client-ip=136.143.188.112 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=collabora.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=collabora.com header.i=daniel.almeida@collabora.com header.b="F1vygAB2" ARC-Seal: i=1; a=rsa-sha256; t=1737032715; cv=none; d=zohomail.com; s=zohoarc; b=aZZIBOvnde6HoJEawyZAaZ0F7UUQY3WmIYfczA5wA2YjlHut2nT7U3vTWtYgktyz6dnNBIuSIbRFKhjGf5b8yUIBc0qqbl2K/qqRFo09RUzeTcmRgy0OCyViE7P5L7+gZWjQN2UlRkCx8m4N77S2d4yDnke+QU5TGK/mWEA96sU= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1737032715; h=Content-Transfer-Encoding:Cc:Cc:Date:Date:From:From:In-Reply-To:MIME-Version:Message-ID:References:Subject:Subject:To:To:Message-Id:Reply-To; bh=gLNt5hpMp+JnNu9GS+NNBAUe84OPwFhj4SDFgzDn6+A=; b=WX0Z7PsMsPqtP0G/2i5LYwidgfUpPl4XLLgNCBO4DpEF/+AfAy5poC77QCVCfGItvwfA+ZgZFF4ov8NrZ1Z0OWLr/REkf3dr2w3DpuVTPx/VbHSYoLJIFeDdoe9EVa0Xb9VChGgO3fhAaZXa7OiM78fMcjYVdFrCS4YMAp6pWas= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass header.i=collabora.com; spf=pass smtp.mailfrom=daniel.almeida@collabora.com; dmarc=pass header.from= DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; t=1737032715; s=zohomail; d=collabora.com; i=daniel.almeida@collabora.com; h=From:From:To:To:Cc:Cc:Subject:Subject:Date:Date:Message-ID:In-Reply-To:References:MIME-Version:Content-Transfer-Encoding:Message-Id:Reply-To; bh=gLNt5hpMp+JnNu9GS+NNBAUe84OPwFhj4SDFgzDn6+A=; b=F1vygAB2FgR109i2zfiTbO9Qj3PUjGVbyfT4nNkRnWXVIIKu9ouQlw6F7rZvKUVj nVFqvsKpDU8sLePkJM57EtKlvRXstoVxFfjdpFTitsCwfXNTXFJrItJh+yfdqOwDuTb w2h4PvEOyO0zojA0M5MkYfLw8JvDeTc2ujPcAE3w= Received: by mx.zohomail.com with SMTPS id 1737032713507931.9572553428109; Thu, 16 Jan 2025 05:05:13 -0800 (PST) From: Daniel Almeida To: ojeda@kernel.org, alex.gaynor@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.mco, benno.lossin@proton.me, a.hindborg@kernel.org, aliceryhl@google.com, tmgross@umich.edu, gregkh@linuxfoundation.org, rafael@kernel.org, dakr@kernel.org, boris.brezillon@collabora.com, robh@kernel.org Cc: Daniel Almeida , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH RESEND v5 2/3] rust: io: mem: add a generic iomem abstraction Date: Thu, 16 Jan 2025 09:56:25 -0300 Message-ID: <20250116125632.65017-3-daniel.almeida@collabora.com> X-Mailer: git-send-email 2.48.0 In-Reply-To: <20250116125632.65017-1-daniel.almeida@collabora.com> References: <20250116125632.65017-1-daniel.almeida@collabora.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-ZohoMailClient: External Content-Type: text/plain; charset="utf-8" Add a generic iomem abstraction to safely read and write ioremapped regions. The reads and writes are done through IoRaw, and are thus checked either at compile-time, if the size of the region is known at that point, or at runtime otherwise. Non-exclusive access to the underlying memory region is made possible to cater to cases where overlapped regions are unavoidable. Signed-off-by: Daniel Almeida Tested-by: Christian Schrefl --- rust/helpers/io.c | 10 +++++ rust/kernel/io.rs | 1 + rust/kernel/io/mem.rs | 98 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 109 insertions(+) create mode 100644 rust/kernel/io/mem.rs diff --git a/rust/helpers/io.c b/rust/helpers/io.c index 3cb47bd01942..cb10060c08ae 100644 --- a/rust/helpers/io.c +++ b/rust/helpers/io.c @@ -106,3 +106,13 @@ resource_size_t rust_helper_resource_size(struct resou= rce *res) return resource_size(res); } =20 +struct resource *rust_helper_request_mem_region(resource_size_t start, res= ource_size_t n, + const char *name) +{ + return request_mem_region(start, n, name); +} + +void rust_helper_release_mem_region(resource_size_t start, resource_size_t= n) +{ + release_mem_region(start, n); +} diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index 566d8b177e01..9ce3482b5ecd 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -7,6 +7,7 @@ use crate::error::{code::EINVAL, Result}; use crate::{bindings, build_assert}; =20 +pub mod mem; pub mod resource; =20 /// Raw representation of an MMIO region. diff --git a/rust/kernel/io/mem.rs b/rust/kernel/io/mem.rs new file mode 100644 index 000000000000..a287dc0898e0 --- /dev/null +++ b/rust/kernel/io/mem.rs @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Generic memory-mapped IO. + +use core::ops::Deref; + +use crate::device::Device; +use crate::devres::Devres; +use crate::io::resource::Resource; +use crate::io::Io; +use crate::io::IoRaw; +use crate::prelude::*; + +/// A generic memory-mapped IO region. +/// +/// Accesses to the underlying region is checked either at compile time, i= f the +/// region's size is known at that point, or at runtime otherwise. +/// +/// Whether `IoMem` represents an exclusive access to the underlying memory +/// region is determined by the caller at creation time, as overlapping ac= cess +/// may be needed in some cases. +/// +/// # Invariants +/// +/// `IoMem` always holds an `IoRaw` inststance that holds a valid pointer = to the +/// start of the I/O memory mapped region. +pub struct IoMem { + io: IoRaw, + res_start: u64, +} + +impl IoMem { + /// Creates a new `IoMem` instance. + pub(crate) fn new(resource: &Resource, device: &Device) -> Result> { + let size =3D resource.size(); + if size =3D=3D 0 { + return Err(EINVAL); + } + + let res_start =3D resource.start(); + + if EXCLUSIVE { + // SAFETY: + // - `res_start` and `size` are read from a presumably valid `= struct resource`. + // - `size` is known not to be zero at this point. + // - `resource.name()` returns a valid C string. + let mem_region =3D unsafe { + bindings::request_mem_region(res_start, size, resource.nam= e().as_char_ptr()) + }; + + if mem_region.is_null() { + return Err(EBUSY); + } + } + + // SAFETY: + // - `res_start` and `size` are read from a presumably valid `stru= ct resource`. + // - `size` is known not to be zero at this point. + let addr =3D unsafe { bindings::ioremap(res_start, size as kernel:= :ffi::c_ulong) }; + if addr.is_null() { + if EXCLUSIVE { + // SAFETY: + // - `res_start` and `size` are read from a presumably val= id `struct resource`. + // - `size` is the same as the one passed to `request_mem_= region`. + unsafe { bindings::release_mem_region(res_start, size) }; + } + return Err(ENOMEM); + } + + let io =3D IoRaw::new(addr as usize, size as usize)?; + let io =3D IoMem { io, res_start }; + let devres =3D Devres::new(device, io, GFP_KERNEL)?; + + Ok(devres) + } +} + +impl Drop for IoMem { + fn drop(&mut self) { + if EXCLUSIVE { + // SAFETY: `res_start` and `io.maxsize()` were the values pass= ed to + // `request_mem_region`. + unsafe { bindings::release_mem_region(self.res_start, self.io.= maxsize() as u64) } + } + + // SAFETY: Safe as by the invariant of `Io`. + unsafe { bindings::iounmap(self.io.addr() as *mut core::ffi::c_voi= d) } + } +} + +impl Deref for IoMem { + type Target =3D Io; + + fn deref(&self) -> &Self::Target { + // SAFETY: Safe as by the invariant of `IoMem`. + unsafe { Io::from_raw(&self.io) } + } +} --=20 2.48.0 From nobody Sat Feb 7 16:33:58 2026 Received: from sender4-pp-f112.zoho.com (sender4-pp-f112.zoho.com [136.143.188.112]) (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 2BC9D1DE8BA; Thu, 16 Jan 2025 13:05:34 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=pass smtp.client-ip=136.143.188.112 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737032736; cv=pass; b=V7/p1W8p/JVIQ6nuaKI1L1qzcIdaZpV1vH9kzmH9v9aIs//Z9OjlZ81MYbNUOUmxkxO7t/K7B40viFc/bXyluGnz+Vnyj0XEI5KBBVHlu9K+fbg+jYERHt+miXCeosg4lLMwJBcSb/1M44pizfQhBl5o01E9Nkgw3ELIqIZ0a+E= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737032736; c=relaxed/simple; bh=E6UU7+rKtRQHDVd+PY4Y9zBTkdz0wuYUfb1LjfbbZjQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=eI18GxZgGL+eho/4R2lPD6w+pCP/0Q0f2Dq/YSeiFRn8OVHiiXm7+cwz98mJW4up6Ter1k3UAlrbhk9p/ikPPXPh1wXwSXHHtTIhTetz/d9u8fd1TK8aclHe3GuG/MckRua0CDyoZ95y1ltcFpsvOcHhGG1XJBMjhXeFSAzIiKE= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com; spf=pass smtp.mailfrom=collabora.com; dkim=pass (1024-bit key) header.d=collabora.com header.i=daniel.almeida@collabora.com header.b=CcZsQcUB; arc=pass smtp.client-ip=136.143.188.112 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=collabora.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=collabora.com header.i=daniel.almeida@collabora.com header.b="CcZsQcUB" ARC-Seal: i=1; a=rsa-sha256; t=1737032719; cv=none; d=zohomail.com; s=zohoarc; b=M15DH3R4vavAJfcXEwgrPADqAi0LYolpoSkEUWM3yPwuRJwJ4YuRiVQPizhhTppN/5lPaGYOf6HGPerF6uJLBZtKaSc6vr1PlywzhDYvySDTBGKCX05157Qg769W0wYAaOmACySYqGMCAV9KCq61zfR0jUKzDfOltl5CwkvDfJ0= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1737032719; h=Content-Transfer-Encoding:Cc:Cc:Date:Date:From:From:In-Reply-To:MIME-Version:Message-ID:References:Subject:Subject:To:To:Message-Id:Reply-To; bh=ic+oqGqc/mAL/ksa+/gIMfrYC8TNVWq2OPJ1ekYeafI=; b=RvT+SWQtE2O5eMEy16OMipAl8eigW0GZlgTV7myTdp191OlEbx6g2gAmi6IO1ddCEbTimUVCESUqAur50LerXmblrLrTjzSYTmn0p2IpkhW0BfQWN+WALnW9EPn4GYqFTdngIiwhG70aUhrBXPRaA3z6nhRsRtoqa1h83/DbQGk= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass header.i=collabora.com; spf=pass smtp.mailfrom=daniel.almeida@collabora.com; dmarc=pass header.from= DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; t=1737032719; s=zohomail; d=collabora.com; i=daniel.almeida@collabora.com; h=From:From:To:To:Cc:Cc:Subject:Subject:Date:Date:Message-ID:In-Reply-To:References:MIME-Version:Content-Transfer-Encoding:Message-Id:Reply-To; bh=ic+oqGqc/mAL/ksa+/gIMfrYC8TNVWq2OPJ1ekYeafI=; b=CcZsQcUBZ9oMxGIB0s+fIILB7hZCl5GtmHjj5VO5WzYZlBzPrmfBrBvSlUpNqDe2 vp4MXb1APWxbhYzuDdWpaZWN8/empZI5oTopR1qlub1ecVF/TBSRxK7Z5YFSK1n1qpz Uwxx0bHBT3WDtE/7ZC6P+W/su5n3W9upCcjtlNfc= Received: by mx.zohomail.com with SMTPS id 1737032716833915.5252914519633; Thu, 16 Jan 2025 05:05:16 -0800 (PST) From: Daniel Almeida To: ojeda@kernel.org, alex.gaynor@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.mco, benno.lossin@proton.me, a.hindborg@kernel.org, aliceryhl@google.com, tmgross@umich.edu, gregkh@linuxfoundation.org, rafael@kernel.org, dakr@kernel.org, boris.brezillon@collabora.com, robh@kernel.org Cc: Daniel Almeida , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org Subject: [PATCH RESEND v5 3/3] rust: platform: allow ioremap of platform resources Date: Thu, 16 Jan 2025 09:56:26 -0300 Message-ID: <20250116125632.65017-4-daniel.almeida@collabora.com> X-Mailer: git-send-email 2.48.0 In-Reply-To: <20250116125632.65017-1-daniel.almeida@collabora.com> References: <20250116125632.65017-1-daniel.almeida@collabora.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-ZohoMailClient: External Content-Type: text/plain; charset="utf-8" The preceding patches added support for resources, and for a general IoMem abstraction, but thus far there is no way to access said IoMem from drivers, as its creation is unsafe and depends on a resource that must be acquired from some device first. Now, allow the ioremap of platform resources themselves, thereby making the IoMem available to platform drivers. Signed-off-by: Daniel Almeida Tested-by: Christian Schrefl --- rust/kernel/platform.rs | 105 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 104 insertions(+), 1 deletion(-) diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs index 50e6b0421813..55c2e0ffd4d1 100644 --- a/rust/kernel/platform.rs +++ b/rust/kernel/platform.rs @@ -5,8 +5,11 @@ //! C header: [`include/linux/platform_device.h`](srctree/include/linux/pl= atform_device.h) =20 use crate::{ - bindings, container_of, device, driver, + bindings, container_of, device, + devres::Devres, + driver, error::{to_result, Result}, + io::{mem::IoMem, resource::Resource}, of, prelude::*, str::CStr, @@ -191,6 +194,106 @@ fn as_raw(&self) -> *mut bindings::platform_device { // embedded in `struct platform_device`. unsafe { container_of!(self.0.as_raw(), bindings::platform_device,= dev) }.cast_mut() } + + /// Maps a platform resource through ioremap() where the size is known= at + /// compile time. + /// + /// # Examples + /// + /// ```no_run + /// use kernel::{bindings, c_str, platform}; + /// + /// fn probe(pdev: &mut platform::Device, /* ... */) -> Result<()> { + /// let offset =3D 0; // Some offset. + /// + /// // If the size is known at compile time, use `ioremap_resource= _sized`. + /// // No runtime checks will apply when reading and writing. + /// let resource =3D pdev.resource(0).ok_or(ENODEV)?; + /// let iomem =3D pdev.ioremap_resource_sized::<42, true>(&resourc= e)?; + /// + /// // Read and write a 32-bit value at `offset`. Calling `try_acc= ess()` on + /// // the `Devres` makes sure that the resource is still valid. + /// let data =3D iomem.try_access().ok_or(ENODEV)?.readl(offset); + /// + /// iomem.try_access().ok_or(ENODEV)?.writel(data, offset); + /// + /// # Ok::<(), Error>(()) + /// } + /// ``` + pub fn ioremap_resource_sized( + &self, + resource: &Resource, + ) -> Result>> { + IoMem::new(resource, self.as_ref()) + } + + /// Maps a platform resource through ioremap(). + /// + /// # Examples + /// + /// ```no_run + /// # use kernel::{bindings, c_str, platform}; + /// + /// fn probe(pdev: &mut platform::Device, /* ... */) -> Result<()> { + /// let offset =3D 0; // Some offset. + /// + /// // Unlike `ioremap_resource_sized`, here the size of the memor= y region + /// // is not known at compile time, so only the `try_read*` and `= try_write*` + /// // family of functions are exposed, leading to runtime checks = on every + /// // access. + /// let resource =3D pdev.resource(0).ok_or(ENODEV)?; + /// let iomem =3D pdev.ioremap_resource::(&resource)?; + /// + /// let data =3D iomem.try_access().ok_or(ENODEV)?.try_readl(offse= t)?; + /// + /// iomem.try_access().ok_or(ENODEV)?.try_writel(data, offset)?; + /// + /// # Ok::<(), Error>(()) + /// } + /// ``` + pub fn ioremap_resource( + &self, + resource: &Resource, + ) -> Result>> { + self.ioremap_resource_sized::<0, EXCLUSIVE>(resource) + } + + /// Returns the resource at `index`, if any. + pub fn resource(&self, index: u32) -> Option<&Resource> { + // SAFETY: `self.as_raw()` returns a valid pointer to a `struct pl= atform_device`. + let resource =3D unsafe { + bindings::platform_get_resource(self.as_raw(), bindings::IORES= OURCE_MEM, index) + }; + + if resource.is_null() { + return None; + } + + // SAFETY: `resource` is a valid pointer to a `struct resource` as + // returned by `platform_get_resource`. + Some(unsafe { Resource::from_ptr(resource) }) + } + + /// Returns the resource with a given `name`, if any. + pub fn resource_by_name(&self, name: &CStr) -> Option<&Resource> { + // SAFETY: `self.as_raw()` returns a valid pointer to a `struct + // platform_device` and `name` points to a valid C string. + let resource =3D unsafe { + bindings::platform_get_resource_byname( + self.as_raw(), + bindings::IORESOURCE_MEM, + name.as_char_ptr(), + ) + }; + + if resource.is_null() { + return None; + } + + // SAFETY: `resource` is a valid pointer to a `struct resource` as + // returned by `platform_get_resource`. + Some(unsafe { Resource::from_ptr(resource) }) + } } =20 impl AsRef for Device { --=20 2.48.0