* [PATCH RESEND v5 1/3] rust: io: add resource abstraction
2025-01-16 12:56 [PATCH RESEND v5 0/3] rust: platform: add Io support Daniel Almeida
@ 2025-01-16 12:56 ` Daniel Almeida
2025-01-16 21:14 ` Christian Schrefl
2025-01-16 12:56 ` [PATCH RESEND v5 2/3] rust: io: mem: add a generic iomem abstraction Daniel Almeida
` (2 subsequent siblings)
3 siblings, 1 reply; 7+ messages in thread
From: Daniel Almeida @ 2025-01-16 12:56 UTC (permalink / raw)
To: ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, benno.lossin,
a.hindborg, aliceryhl, tmgross, gregkh, rafael, dakr,
boris.brezillon, robh
Cc: Daniel Almeida, rust-for-linux, linux-kernel
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 <daniel.almeida@collabora.com>
---
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_helper.h
index e9fdceb568b8..f9c2eedb5b9b 100644
--- a/rust/bindings/bindings_helper.h
+++ b/rust/bindings/bindings_helper.h
@@ -16,6 +16,7 @@
#include <linux/file.h>
#include <linux/firmware.h>
#include <linux/fs.h>
+#include <linux/ioport.h>
#include <linux/jiffies.h>
#include <linux/jump_label.h>
#include <linux/mdio.h>
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
#include <linux/io.h>
+#include <linux/ioport.h>
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};
+pub mod resource;
+
/// Raw representation of an MMIO region.
///
/// By itself, the existence of an instance of this structure does not provide 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<bindings::resource>);
+
+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 will
+ /// point at a valid `bindings::resource`
+ ///
+ /// The caller must also ensure that the `Resource` is only accessed via 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<bindings::resource>`.
+ unsafe { &*ptr.cast() }
+ }
+
+ /// Returns the size of the resource.
+ pub fn size(&self) -> bindings::resource_size_t {
+ let inner = 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 = 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 = self.0.get();
+ // SAFETY: safe as per the invariants of `Resource`
+ unsafe { CStr::from_char_ptr((*inner).name) }
+ }
+}
--
2.48.0
^ permalink raw reply related [flat|nested] 7+ messages in thread* Re: [PATCH RESEND v5 1/3] rust: io: add resource abstraction
2025-01-16 12:56 ` [PATCH RESEND v5 1/3] rust: io: add resource abstraction Daniel Almeida
@ 2025-01-16 21:14 ` Christian Schrefl
0 siblings, 0 replies; 7+ messages in thread
From: Christian Schrefl @ 2025-01-16 21:14 UTC (permalink / raw)
To: Daniel Almeida, ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh,
benno.lossin, a.hindborg, aliceryhl, tmgross, gregkh, rafael,
dakr, boris.brezillon, robh
Cc: rust-for-linux, linux-kernel
Hi Daniel
On 16.01.25 1:56 PM, Daniel Almeida wrote:
> 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 <daniel.almeida@collabora.com>
> ---
> 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_helper.h
> index e9fdceb568b8..f9c2eedb5b9b 100644
> --- a/rust/bindings/bindings_helper.h
> +++ b/rust/bindings/bindings_helper.h
> @@ -16,6 +16,7 @@
> #include <linux/file.h>
> #include <linux/firmware.h>
> #include <linux/fs.h>
> +#include <linux/ioport.h>
> #include <linux/jiffies.h>
> #include <linux/jump_label.h>
> #include <linux/mdio.h>
> 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
>
> #include <linux/io.h>
> +#include <linux/ioport.h>
>
> 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};
>
> +pub mod resource;
> +
> /// Raw representation of an MMIO region.
> ///
> /// By itself, the existence of an instance of this structure does not provide 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<bindings::resource>);
> +
> +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 will
> + /// point at a valid `bindings::resource`
> + ///
> + /// The caller must also ensure that the `Resource` is only accessed via 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<bindings::resource>`.
> + unsafe { &*ptr.cast() }
> + }
> +
> + /// Returns the size of the resource.
> + pub fn size(&self) -> bindings::resource_size_t {
> + let inner = 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 {
Please use bindings::resource_size_t to be compatible with 32-bit architectures.
> + let inner = 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 = self.0.get();
> + // SAFETY: safe as per the invariants of `Resource`
> + unsafe { CStr::from_char_ptr((*inner).name) }
> + }
> +}
Cheers
Christian
^ permalink raw reply [flat|nested] 7+ messages in thread
* [PATCH RESEND v5 2/3] rust: io: mem: add a generic iomem abstraction
2025-01-16 12:56 [PATCH RESEND v5 0/3] rust: platform: add Io support Daniel Almeida
2025-01-16 12:56 ` [PATCH RESEND v5 1/3] rust: io: add resource abstraction Daniel Almeida
@ 2025-01-16 12:56 ` Daniel Almeida
2025-01-16 21:15 ` Christian Schrefl
2025-01-16 12:56 ` [PATCH RESEND v5 3/3] rust: platform: allow ioremap of platform resources Daniel Almeida
2025-01-16 21:24 ` [PATCH RESEND v5 0/3] rust: platform: add Io support Christian Schrefl
3 siblings, 1 reply; 7+ messages in thread
From: Daniel Almeida @ 2025-01-16 12:56 UTC (permalink / raw)
To: ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, benno.lossin,
a.hindborg, aliceryhl, tmgross, gregkh, rafael, dakr,
boris.brezillon, robh
Cc: Daniel Almeida, rust-for-linux, linux-kernel
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 <daniel.almeida@collabora.com>
---
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 resource *res)
return resource_size(res);
}
+struct resource *rust_helper_request_mem_region(resource_size_t start, resource_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};
+pub mod mem;
pub mod resource;
/// 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, if 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 access
+/// 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<const SIZE: usize = 0, const EXCLUSIVE: bool = true> {
+ io: IoRaw<SIZE>,
+ res_start: u64,
+}
+
+impl<const SIZE: usize, const EXCLUSIVE: bool> IoMem<SIZE, EXCLUSIVE> {
+ /// Creates a new `IoMem` instance.
+ pub(crate) fn new(resource: &Resource, device: &Device) -> Result<Devres<Self>> {
+ let size = resource.size();
+ if size == 0 {
+ return Err(EINVAL);
+ }
+
+ let res_start = 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 = unsafe {
+ bindings::request_mem_region(res_start, size, resource.name().as_char_ptr())
+ };
+
+ if mem_region.is_null() {
+ return Err(EBUSY);
+ }
+ }
+
+ // SAFETY:
+ // - `res_start` and `size` are read from a presumably valid `struct resource`.
+ // - `size` is known not to be zero at this point.
+ let addr = 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 valid `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 = IoRaw::new(addr as usize, size as usize)?;
+ let io = IoMem { io, res_start };
+ let devres = Devres::new(device, io, GFP_KERNEL)?;
+
+ Ok(devres)
+ }
+}
+
+impl<const SIZE: usize, const EXCLUSIVE: bool> Drop for IoMem<SIZE, EXCLUSIVE> {
+ fn drop(&mut self) {
+ if EXCLUSIVE {
+ // SAFETY: `res_start` and `io.maxsize()` were the values passed 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_void) }
+ }
+}
+
+impl<const SIZE: usize, const EXCLUSIVE: bool> Deref for IoMem<SIZE, EXCLUSIVE> {
+ type Target = Io<SIZE>;
+
+ fn deref(&self) -> &Self::Target {
+ // SAFETY: Safe as by the invariant of `IoMem`.
+ unsafe { Io::from_raw(&self.io) }
+ }
+}
--
2.48.0
^ permalink raw reply related [flat|nested] 7+ messages in thread* Re: [PATCH RESEND v5 2/3] rust: io: mem: add a generic iomem abstraction
2025-01-16 12:56 ` [PATCH RESEND v5 2/3] rust: io: mem: add a generic iomem abstraction Daniel Almeida
@ 2025-01-16 21:15 ` Christian Schrefl
0 siblings, 0 replies; 7+ messages in thread
From: Christian Schrefl @ 2025-01-16 21:15 UTC (permalink / raw)
To: Daniel Almeida, ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh,
benno.lossin, a.hindborg, aliceryhl, tmgross, gregkh, rafael,
dakr, boris.brezillon, robh
Cc: rust-for-linux, linux-kernel
Hi Daniel
On 16.01.25 1:56 PM, Daniel Almeida wrote:
> 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 <daniel.almeida@collabora.com>
> ---
> 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 resource *res)
> return resource_size(res);
> }
>
> +struct resource *rust_helper_request_mem_region(resource_size_t start, resource_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};
>
> +pub mod mem;
> pub mod resource;
>
> /// 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, if 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 access
> +/// 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<const SIZE: usize = 0, const EXCLUSIVE: bool = true> {
> + io: IoRaw<SIZE>,
> + res_start: u64,
Please use bindings::resource_size_t here to to be compatible with 32-bit architectures.
> +}
> +
> +impl<const SIZE: usize, const EXCLUSIVE: bool> IoMem<SIZE, EXCLUSIVE> {
> + /// Creates a new `IoMem` instance.
> + pub(crate) fn new(resource: &Resource, device: &Device) -> Result<Devres<Self>> {
> + let size = resource.size();
> + if size == 0 {
> + return Err(EINVAL);
> + }
> +
> + let res_start = 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 = unsafe {
> + bindings::request_mem_region(res_start, size, resource.name().as_char_ptr())
> + };
> +
> + if mem_region.is_null() {
> + return Err(EBUSY);
> + }
> + }
> +
> + // SAFETY:
> + // - `res_start` and `size` are read from a presumably valid `struct resource`.
> + // - `size` is known not to be zero at this point.
> + let addr = 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 valid `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 = IoRaw::new(addr as usize, size as usize)?;
> + let io = IoMem { io, res_start };
> + let devres = Devres::new(device, io, GFP_KERNEL)?;
> +
> + Ok(devres)
> + }
> +}
> +
> +impl<const SIZE: usize, const EXCLUSIVE: bool> Drop for IoMem<SIZE, EXCLUSIVE> {
> + fn drop(&mut self) {
> + if EXCLUSIVE {
> + // SAFETY: `res_start` and `io.maxsize()` were the values passed to
> + // `request_mem_region`.
> + unsafe { bindings::release_mem_region(self.res_start, self.io.maxsize() as u64) }
Please use bindings::resource_size_t here as well.
> + }
> +
> + // SAFETY: Safe as by the invariant of `Io`.
> + unsafe { bindings::iounmap(self.io.addr() as *mut core::ffi::c_void) }
> + }
> +}
> +
> +impl<const SIZE: usize, const EXCLUSIVE: bool> Deref for IoMem<SIZE, EXCLUSIVE> {
> + type Target = Io<SIZE>;
> +
> + fn deref(&self) -> &Self::Target {
> + // SAFETY: Safe as by the invariant of `IoMem`.
> + unsafe { Io::from_raw(&self.io) }
> + }
> +}
Cheers
Christian
^ permalink raw reply [flat|nested] 7+ messages in thread
* [PATCH RESEND v5 3/3] rust: platform: allow ioremap of platform resources
2025-01-16 12:56 [PATCH RESEND v5 0/3] rust: platform: add Io support Daniel Almeida
2025-01-16 12:56 ` [PATCH RESEND v5 1/3] rust: io: add resource abstraction Daniel Almeida
2025-01-16 12:56 ` [PATCH RESEND v5 2/3] rust: io: mem: add a generic iomem abstraction Daniel Almeida
@ 2025-01-16 12:56 ` Daniel Almeida
2025-01-16 21:24 ` [PATCH RESEND v5 0/3] rust: platform: add Io support Christian Schrefl
3 siblings, 0 replies; 7+ messages in thread
From: Daniel Almeida @ 2025-01-16 12:56 UTC (permalink / raw)
To: ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, benno.lossin,
a.hindborg, aliceryhl, tmgross, gregkh, rafael, dakr,
boris.brezillon, robh
Cc: Daniel Almeida, rust-for-linux, linux-kernel
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 <daniel.almeida@collabora.com>
---
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/platform_device.h)
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 = 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 = pdev.resource(0).ok_or(ENODEV)?;
+ /// let iomem = pdev.ioremap_resource_sized::<42, true>(&resource)?;
+ ///
+ /// // Read and write a 32-bit value at `offset`. Calling `try_access()` on
+ /// // the `Devres` makes sure that the resource is still valid.
+ /// let data = iomem.try_access().ok_or(ENODEV)?.readl(offset);
+ ///
+ /// iomem.try_access().ok_or(ENODEV)?.writel(data, offset);
+ ///
+ /// # Ok::<(), Error>(())
+ /// }
+ /// ```
+ pub fn ioremap_resource_sized<const SIZE: usize, const EXCLUSIVE: bool>(
+ &self,
+ resource: &Resource,
+ ) -> Result<Devres<IoMem<SIZE, EXCLUSIVE>>> {
+ 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 = 0; // Some offset.
+ ///
+ /// // Unlike `ioremap_resource_sized`, here the size of the memory 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 = pdev.resource(0).ok_or(ENODEV)?;
+ /// let iomem = pdev.ioremap_resource::<true>(&resource)?;
+ ///
+ /// let data = iomem.try_access().ok_or(ENODEV)?.try_readl(offset)?;
+ ///
+ /// iomem.try_access().ok_or(ENODEV)?.try_writel(data, offset)?;
+ ///
+ /// # Ok::<(), Error>(())
+ /// }
+ /// ```
+ pub fn ioremap_resource<const EXCLUSIVE: bool>(
+ &self,
+ resource: &Resource,
+ ) -> Result<Devres<IoMem<0, EXCLUSIVE>>> {
+ 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 platform_device`.
+ let resource = unsafe {
+ bindings::platform_get_resource(self.as_raw(), bindings::IORESOURCE_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 = 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) })
+ }
}
impl AsRef<device::Device> for Device {
--
2.48.0
^ permalink raw reply related [flat|nested] 7+ messages in thread* Re: [PATCH RESEND v5 0/3] rust: platform: add Io support
2025-01-16 12:56 [PATCH RESEND v5 0/3] rust: platform: add Io support Daniel Almeida
` (2 preceding siblings ...)
2025-01-16 12:56 ` [PATCH RESEND v5 3/3] rust: platform: allow ioremap of platform resources Daniel Almeida
@ 2025-01-16 21:24 ` Christian Schrefl
3 siblings, 0 replies; 7+ messages in thread
From: Christian Schrefl @ 2025-01-16 21:24 UTC (permalink / raw)
To: Daniel Almeida, ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh,
benno.lossin, a.hindborg, aliceryhl, tmgross, gregkh, rafael,
dakr, boris.brezillon, robh
Cc: rust-for-linux, linux-kernel
Hi Daniel
On 16.01.25 1:56 PM, Daniel Almeida wrote:
> Changes in v5:
>
> - resend v5, as the r4l list was not cc'd
> - use srctree where applicable in the docs (Alice)
> - Remove 'mut' in Resource::from_ptr() (Alice)
> - Add 'invariants' section for Resource (Alice)
> - Fix typos in mem.rs (Alice)
> - Turn 'exclusive' into a const generic (Alice)
> - Fix example in platform.rs (Alice)
> - Rework the resource.is_null() check (Alice)
> - Refactor IoMem::new() to return DevRes<IoMem> directly (Danilo)
>
> link to v4: https://lore.kernel.org/rust-for-linux/20250109133057.243751-1-daniel.almeida@collabora.com/
>
> Changes in v4:
>
> - Rebased on top of driver-core-next
> - Split series in multiple patches (Danilo)
> - Move IoMem and Resource into its own files (Danilo)
> - Fix a missing "if exclusive {...}" check (Danilo)
> - Fixed the example, since it was using the old API (Danilo)
> - Use Opaque in `Resource`, instead of NonNull and PhantomData (Boqun)
> - Highlight that non-exclusive access to the iomem might be required in some cases
> - Fixed the safety comment in IoMem::deref()
>
> Link to v3: https://lore.kernel.org/rust-for-linux/20241211-topic-panthor-rs-platform_io_support-v3-1-08ba707e5e3b@collabora.com/
>
> Changes in v3:
> - Rebased on top of v5 for the PCI/Platform abstractions
> - platform_get_resource is now called only once when calling ioremap
> - Introduced a platform::Resource type, which is bound to the lifetime of the
> platform Device
> - Allow retrieving resources from the platform device either by index or
> name
> - Make request_mem_region() optional
> - Use resource.name() in request_mem_region
> - Reword the example to remove an unaligned, out-of-bounds offset
> - Update the safety requirements of platform::IoMem
>
> Changes in v2:
> - reworked the commit message
> - added missing request_mem_region call (Thanks Alice, Danilo)
> - IoMem::new() now takes the platform::Device, the resource number and
> the name, instead of an address and a size (thanks, Danilo)
> - Added a new example for both sized and unsized versions of IoMem.
> - Compiled the examples using kunit.py (thanks for the tip, Alice!)
> - Removed instances of `foo as _`. All `as` casts now spell out the actual
> type.
> - Now compiling with CLIPPY=1 (I realized I had forgotten, sorry)
> - Rebased on top of rust-next to check for any warnings given the new
> unsafe lints.
>
> Daniel Almeida (3):
> rust: io: add resource abstraction
> rust: io: mem: add a generic iomem abstraction
> rust: platform: allow ioremap of platform resources
>
> rust/bindings/bindings_helper.h | 1 +
> rust/helpers/io.c | 17 ++++++
> rust/kernel/io.rs | 3 +
> rust/kernel/io/mem.rs | 98 +++++++++++++++++++++++++++++
> rust/kernel/io/resource.rs | 53 ++++++++++++++++
> rust/kernel/platform.rs | 105 +++++++++++++++++++++++++++++++-
> 6 files changed, 276 insertions(+), 1 deletion(-)
> create mode 100644 rust/kernel/io/mem.rs
> create mode 100644 rust/kernel/io/resource.rs
>
I've tested this patch-set with my ARM 32-bit arm patches[0] on a De1Soc (Fpga + Arm Cortex A9).
I've got it to work by changing the three instances of u64 (mentioned on the individual patches) to bindings::resource_size_t.
I used a small Fpga configuration that allows me to change a led from the kernel driver.
So with these fixed:
Tested-by: Christian Schrefl <chrisi.schrefl@gmail.com>
[0]: https://github.com/onestacked/linux/commit/f84be45f7311ea5b5a76123028f9fb8fda9f9e7f
Cheers
Christian
^ permalink raw reply [flat|nested] 7+ messages in thread