rust: platform: add Io support
Subsystems (3)
Daniel Almeida
maintainerv5 cover rust: platform: add Io support
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/[email protected]/
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()
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
Signature · 1 line
2.48.0
Daniel Almeida
maintainerPATCH RESEND v5 1/3 rust: io: add resource abstraction
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.
--- 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
rust/bindings/bindings_helper.h +1 -0
@@ -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>
rust/helpers/io.c +7 -0
@@ -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); +} +
rust/kernel/io.rs +2 -0
@@ -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
rust/kernel/io/resource.rs new file +53 -0
53 lines not on this page · raw message
Signature · 1 line
2.48.0
Re: [PATCH RESEND v5 1/3] rust: io: add resource abstraction
Hi Daniel
Quoted 100 lines · Daniel Almeida
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 <[email protected]>--- 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.rsrust/bindings/bindings_helper.h +1
-0@@ -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> rust/helpers/io.c +7
-0@@ -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); +} +rust/kernel/io.rs +2
-0@@ -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 rust/kernel/io/resource.rs new file +31
-0@@ -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 ) -> &'aSelf { +// SAFETY: Self is a transparent wrapper around `Opaque<bindings::resource>`. +unsafe { &*ptr.cast () } + }
rust/kernel/io/resource.rs line 41
Quoted 10 lines
rust/kernel/io/resource.rs new file +10
-0+ +/// 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.
rust/kernel/io/resource.rs line 53
Quoted 12 lines
rust/kernel/io/resource.rs new file +12
-0+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
Daniel Almeida
maintainerPATCH RESEND v5 2/3 rust: io: mem: add a generic iomem abstraction
In reply to Daniel AlmeidaAdd 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.
--- 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
rust/helpers/io.c +10 -0
@@ -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); +}
rust/kernel/io.rs +1 -0
@@ -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.
rust/kernel/io/mem.rs new file +98 -0
98 lines not on this page · raw message
Signature · 1 line
2.48.0
Re: [PATCH RESEND v5 2/3] rust: io: mem: add a generic iomem abstraction
Hi Daniel
Quoted 73 lines · Daniel Almeida
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 <[email protected]>--- 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.rsrust/helpers/io.c +10
-0@@ -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); +}rust/kernel/io.rs +1
-0@@ -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. rust/kernel/io/mem.rs new file +19
-0@@ -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
rust/kernel/io/mem.rs line 29
Quoted 10 lines
rust/kernel/io/mem.rs new file +10
-0+/// 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.
Quoted 44 lines
rust/kernel/io/mem.rs new file +44
-0+} + +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, sizeas 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 (addras usize , sizeas usize )?; +let io =IoMem { io, res_start }; +let devres =Devres ::new (device, io,GFP_KERNEL )?; +
rust/kernel/io/mem.rs line 83
Quoted 10 lines
rust/kernel/io/mem.rs new file +10
-0+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.
Quoted 5 lines
rust/kernel/io/mem.rs new file +5
-0+ } + +// SAFETY: Safe as by the invariant of `Io`. +unsafe { bindings::iounmap (self.io.addr ()as *mut core::ffi::c_void ) } + }
rust/kernel/io/mem.rs line 98
Quoted 10 lines
rust/kernel/io/mem.rs new file +10
-0+} + +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
Daniel Almeida
maintainerPATCH RESEND v5 3/3 rust: platform: allow ioremap of platform resources
In reply to Daniel AlmeidaThe 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.
--- rust/kernel/platform.rs | 105 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 104 insertions(+), 1 deletion(-)
rust/kernel/platform.rs +104 -1
@@ -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 {
Signature · 1 line
2.48.0
Hi Daniel
Quoted 57 lines · Daniel Almeida
Changes in v5:
- resend v5, as the r4l list was not cc'd
- use srctree where applicable in the docs (Alice)
- Remove 'mut' inResource::from_ptr()(Alice)
- Add 'invariants' section for Resource (Alice)
- Fix typos inmem.rs(Alice)
- Turn 'exclusive' into a const generic (Alice)
- Fix example inplatform.rs(Alice)
- Rework theresource.is_null()check (Alice)
- RefactorIoMem::new()to return DevRes<IoMem> directly (Danilo)link to v4: https://lore.kernel.org/rust-for-linux/[email protected]/
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 inResource, instead of NonNull and PhantomData (Boqun)
- Highlight that non-exclusive access to the iomem might be required in some cases
- Fixed the safety comment inIoMem::deref()Changes in v3:
- Rebased on top of v5 for the PCI/Platform abstractions
-platform_get_resourceis now called only once when calling ioremap
- Introduced aplatform::Resourcetype, which is bound to the lifetime of the platform Device
- Allow retrieving resources from the platform device either by index or name
- Makerequest_mem_region()optional
- Useresource.name()inrequest_mem_region
- Reword the example to remove an unaligned, out-of-bounds offset
- Update the safety requirements ofplatform::IoMemChanges in v2:
- reworked the commit message
- added missingrequest_mem_regioncall (Thanks Alice, Danilo)
-IoMem::new()now takes theplatform::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 usingkunit.py(thanks for the tip, Alice!)
- Removed instances offoo as _. Allascasts 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
Quoted 10 lines
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:
[0]: https://github.com/onestacked/linux/commit/f84be45f7311ea5b5a76123028f9fb8fda9f9e7f
Cheers
Christian