Add dma coherent allocator abstraction
Subsystems (2)
Abdiel Janulgue
reviewerv10 cover Add dma coherent allocator abstraction
Changes since v9:
- Use ARef<Device> in the constructor arguments, docs clarification avoid manually dropping the refcount for the device in into_parts(), use
add() instead of wrapping_add() in the pointer arithmetic for performance (Alice Ryhl).
- Link to v9: https://lore.kernel.org/all/[email protected]/
Changes since v8:
- Add MAINTAINERS entry
- Fix build issues due to switch from core::ffi to crate:ffi in bindgen.
- Ensure the wrapped attribute is non-pub in struct Attrs, declare it #[repr(transparent)] as well (Daniel Sedlak)
Changes since v7:
- Remove cpu_buf() and cpu_buf_mut() as exporting a r/w interface via a slice is undefined behaviour due to slice's requirement that the underlying pointer should not be modified (Alice Ryhl, Robin Murphy).
- Reintroduce r/w helpers instead which includes proper safety invariants (Daniel Almeida).
Changes since v6:
- Include the dma_attrs in the constructor, use alloc::Flags as inpiration
Changes since v5:
- Remove unnecessary lifetime annotation when returning the CPU buffer.
Changes since v4:
- Documentation and example fixes, use Markdown formatting (Miguel Ojeda).
- Discard read()/write() helpers to remove bound on Copy and fix overhead (Daniel Almeida).
- Improve error-handling in the constructor block (Andreas Hindborg).
Changes since v3:
- Reject ZST types by checking the type size in the constructor in addition to requiring FromBytes/AsBytes traits for the type (Alice Ryhl).
Changes since v2:
- Fixed missing header for generating the bindings.
Changes since v1:
- Fix missing info in commit log where EOVERFLOW is used.
- Restrict the dma coherent allocator to numeric types for now for valid behaviour (Daniel Almeida).
- Build slice dynamically.
Abdiel Janulgue (3):
rust: error: Add EOVERFLOW
rust: add dma coherent allocator abstraction.
MAINTAINERS: add entry for Rust dma mapping helpers device driver API
MAINTAINERS | 10 ++ rust/bindings/bindings_helper.h | 1 + rust/kernel/dma.rs | 281 ++++++++++++++++++++++++++++++++ rust/kernel/error.rs | 1 + rust/kernel/lib.rs | 1 + 5 files changed, 294 insertions(+) create mode 100644 rust/kernel/dma.rs
base-commit: ceff0757f5dafb5be5205988171809c877b1d3e3
Signature · 1 line
2.43.0
Abdiel Janulgue
reviewerPATCH v10 1/3 rust: error: Add EOVERFLOW
Trivial addition for missing EOVERFLOW error. This is used by a subsequent patch that might require returning EOVERFLOW as a result of checked_mul.
--- rust/kernel/error.rs | 1 + 1 file changed, 1 insertion(+)
rust/kernel/error.rs +1 -0
@@ -64,6 +64,7 @@ macro_rules! declare_err {declare_err! (EPIPE ,"Broken pipe." );declare_err! (EDOM ,"Math argument out of domain of func." );declare_err! (ERANGE ,"Math result not representable." ); +declare_err! (EOVERFLOW ,"Value too large for defined data type." );declare_err! (ERESTARTSYS ,"Restart the system call." );declare_err! (ERESTARTNOINTR ,"System call was interrupted by a signal and will be restarted." );declare_err! (ERESTARTNOHAND ,"Restart if no handler." );
Signature · 1 line
2.43.0
Abdiel Janulgue
reviewerPATCH v10 2/3 rust: add dma coherent allocator abstraction.
In reply to Abdiel JanulgueAdd a simple dma coherent allocator rust abstraction. Based on Andreas Hindborg's dma abstractions from the rnvme driver, which was also based on earlier work by Wedson Almeida Filho.
--- rust/bindings/bindings_helper.h | 1 + rust/kernel/dma.rs | 281 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 3 files changed, 283 insertions(+) create mode 100644 rust/kernel/dma.rs
rust/bindings/bindings_helper.h +1 -0
@@ -11,6 +11,7 @@#include <linux/blk_types.h> #include <linux/blkdev.h> #include <linux/cred.h> +#include <linux/dma-mapping.h> #include <linux/errname.h> #include <linux/ethtool.h> #include <linux/file.h>
rust/kernel/dma.rs new file +281 -0
281 lines not on this page · raw message
rust/kernel/lib.rs +1 -0
@@ -37,6 +37,7 @@pub mod build_assert;pub mod cred;pub mod device; +pub mod dma;pub mod error;#[cfg( CONFIG_RUST_FW_LOADER_ABSTRACTIONS )] pub mod firmware;
Signature · 1 line
2.43.0
Alice Ryhl
reviewerRe: [PATCH v10 2/3] rust: add dma coherent allocator abstraction.
Quoted 216 lines · Abdiel Janulgue
Add a simple dma coherent allocator rust abstraction. Based on Andreas Hindborg's dma abstractions from the rnvme driver, which was also based on earlier work by Wedson Almeida Filho.
Signed-off-by Abdiel Janulgue <[email protected]>--- rust/bindings/bindings_helper.h | 1 + rust/kernel/dma.rs | 281 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 3 files changed, 283 insertions(+) create mode 100644 rust/kernel/dma.rsrust/bindings/bindings_helper.h +1
-0@@ -11,6 +11,7 @@#include <linux/blk_types.h> #include <linux/blkdev.h> #include <linux/cred.h> +#include <linux/dma-mapping.h> #include <linux/errname.h> #include <linux/ethtool.h> #include <linux/file.h> rust/kernel/dma.rs new file +185
-0@@ -0,0 +1,281 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Direct memory access (DMA). +//! +//! C header: [`include/linux/dma-mapping.h`](srctree/include/linux/dma-mapping.h) + +use crate ::{ + bindings, build_assert, + device::Device , + error::code::*, + error::Result , + transmute::{AsBytes ,FromBytes }, + types::ARef , +}; + +/// Possible attributes associated with a DMA mapping. +/// +/// They can be combined with the operators `|`, `&`, and `!`. +/// +/// Values can be used from the [`attrs`] module. +#[derive( Clone , Copy , PartialEq )] +#[repr(transparent)] +pub struct Attrs (u32 ); + +impl Attrs { +/// Get the raw representation of this attribute. +pub (crate )fn as_raw (self) ->crate ::ffi::c_ulong { + self.0 as _ + } + +/// Check whether `flags` is contained in `self`. +pub fn contains (self, flags:Attrs ) ->bool { + (self & flags) == flags + } +} + +impl core::ops::BitOr for Attrs { +type Output =Self ; +fn bitor (self, rhs:Self ) ->Self ::Output { +Self (self.0 | rhs.0 ) + } +} + +impl core::ops::BitAnd for Attrs { +type Output =Self ; +fn bitand (self, rhs:Self ) ->Self ::Output { +Self (self.0 & rhs.0 ) + } +} + +impl core::ops::Not for Attrs { +type Output =Self ; +fn not (self) ->Self ::Output { +Self (!self.0 ) + } +} + +/// DMA mapping attrributes. +pub mod attrs { +use super ::Attrs ; + +/// Specifies that reads and writes to the mapping may be weakly ordered, that is that reads +/// and writes may pass each other. +pub const DMA_ATTR_WEAK_ORDERING :Attrs =Attrs (bindings::DMA_ATTR_WEAK_ORDERING ); + +/// Specifies that writes to the mapping may be buffered to improve performance. +pub const DMA_ATTR_WRITE_COMBINE :Attrs =Attrs (bindings::DMA_ATTR_WRITE_COMBINE ); + +/// Lets the platform to avoid creating a kernel virtual mapping for the allocated buffer. +pub const DMA_ATTR_NO_KERNEL_MAPPING :Attrs =Attrs (bindings::DMA_ATTR_NO_KERNEL_MAPPING ); + +/// Allows platform code to skip synchronization of the CPU cache for the given buffer assuming +/// that it has been already transferred to 'device' domain. +pub const DMA_ATTR_SKIP_CPU_SYNC :Attrs =Attrs (bindings::DMA_ATTR_SKIP_CPU_SYNC ); + +/// Forces contiguous allocation of the buffer in physical memory. +pub const DMA_ATTR_FORCE_CONTIGUOUS :Attrs =Attrs (bindings::DMA_ATTR_FORCE_CONTIGUOUS ); + +/// This is a hint to the DMA-mapping subsystem that it's probably not worth the time to try +/// to allocate memory to in a way that gives better TLB efficiency. +pub const DMA_ATTR_ALLOC_SINGLE_PAGES :Attrs =Attrs (bindings::DMA_ATTR_ALLOC_SINGLE_PAGES ); + +/// This tells the DMA-mapping subsystem to suppress allocation failure reports (similarly to +/// __GFP_NOWARN). +pub const DMA_ATTR_NO_WARN :Attrs =Attrs (bindings::DMA_ATTR_NO_WARN ); + +/// Used to indicate that the buffer is fully accessible at an elevated privilege level (and +/// ideally inaccessible or at least read-only at lesser-privileged levels). +pub const DMA_ATTR_PRIVILEGED :Attrs =Attrs (bindings::DMA_ATTR_PRIVILEGED ); +} + +/// An abstraction of the `dma_alloc_coherent` API. +/// +/// This is an abstraction around the `dma_alloc_coherent` API which is used to allocate and map +/// large consistent DMA regions. +/// +/// A [`CoherentAllocation`] instance contains a pointer to the allocated region (in the +/// processor's virtual address space) and the device address which can be given to the device +/// as the DMA address base of the region. The region is released once [`CoherentAllocation`] +/// is dropped. +/// +/// # Invariants +/// +/// For the lifetime of an instance of [`CoherentAllocation`], the cpu address is a valid pointer +/// to an allocated region of consistent memory and we hold a reference to the device. +pub struct CoherentAllocation <T :AsBytes +FromBytes > { + dev:ARef <Device >, + dma_handle: bindings::dma_addr_t , + count:usize , + cpu_addr: *mut T , + dma_attrs:Attrs , +} + +impl <T :AsBytes +FromBytes >CoherentAllocation <T > { +/// Allocates a region of `size_of::<T> * count` of consistent memory. +/// +/// # Examples +/// +/// ``` +/// use kernel::device::Device; +/// use kernel::dma::{attrs::*, CoherentAllocation}; +/// +/// # fn test(dev: &Device) -> Result { +/// let c: CoherentAllocation<u64> = CoherentAllocation::alloc_attrs(dev.into(), 4, GFP_KERNEL, +/// DMA_ATTR_NO_WARN)?; +/// # Ok::<(), Error>(()) } +/// ``` +pub fn alloc_attrs ( + dev:ARef <Device >, + count:usize , + gfp_flags: kernel::alloc::Flags , + dma_attrs:Attrs , + ) ->Result <CoherentAllocation <T >> { +build_assert! ( + core::mem::size_of ::<T >() >0 , +"It doesn't make sense for the allocated type to be a ZST" + ); + +let size = count + .checked_mul (core::mem::size_of ::<T >()) + .ok_or (EOVERFLOW )?; +let mut dma_handle =0 ; +// SAFETY: device pointer is guaranteed as valid by invariant on `Device`. +// We ensure that we catch the failure on this function and throw an ENOMEM +let ret =unsafe { + bindings::dma_alloc_attrs ( + dev.as_raw (), + size, + &mut dma_handle, + gfp_flags.as_raw (), + dma_attrs.as_raw (), + ) + }; +if ret.is_null () { +return Err (ENOMEM ); + } +// INVARIANT: We just successfully allocated a coherent region which is accessible for +// `count` elements, hence the cpu address is valid. We also hold a refcounted reference +// to the device. +Ok (Self { + dev, + dma_handle, + count, + cpu_addr: retas *mut T , + dma_attrs, + }) + } + +/// Performs the same functionality as `alloc_attrs`, except the `dma_attrs` is 0 by default. +pub fn alloc_coherent ( + dev:ARef <Device >, + count:usize , + gfp_flags: kernel::alloc::Flags , + ) ->Result <CoherentAllocation <T >> { +CoherentAllocation ::alloc_attrs (dev, count, gfp_flags,Attrs (0 )) + } + +/// Returns the device, base address, dma handle, attributes and the size of the +/// allocated region. +/// +/// The caller takes ownership of the returned resources, i.e., will have the responsibility +/// in calling `bindings::dma_free_attrs`. The allocated region is valid as long as +/// the returned device exists. +pub fn into_parts ( + self,
rust/kernel/dma.rs line 195
Quoted 10 lines
rust/kernel/dma.rs new file +10
-0+ ) -> ( +ARef <Device >, + *mut T , + bindings::dma_addr_t , +crate ::ffi::c_ulong , +usize , + ) { +let size = self.count * core::mem::size_of ::<T >(); +let ret = ( + self.dev.clone(),
Calling clone here increments the refcount, but you don't want to do that since it leaks a count.
otherwise lgtm
Alice
Abdiel Janulgue
reviewerRe: [PATCH v10 2/3] rust: add dma coherent allocator abstraction.
Quoted 223 lines · Alice Ryhl
Quoted 221 lines · Abdiel Janulgue
Add a simple dma coherent allocator rust abstraction. Based on Andreas Hindborg's dma abstractions from the rnvme driver, which was also based on earlier work by Wedson Almeida Filho.
Signed-off-by Abdiel Janulgue <[email protected]>--- rust/bindings/bindings_helper.h | 1 + rust/kernel/dma.rs | 281 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 3 files changed, 283 insertions(+)create mode 100644
rust/kernel/dma.rsrust/bindings/bindings_helper.h +1
-0@@ -11,6 +11,7 @@#include <linux/blk_types.h> #include <linux/blkdev.h> #include <linux/cred.h> +#include <linux/dma-mapping.h> #include <linux/errname.h> #include <linux/ethtool.h> #include <linux/file.h> rust/kernel/dma.rs new file +190
-0@@ -0,0 +1,281 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Direct memory access (DMA). +//! +//! C header: [`include/linux/dma-mapping.h`](srctree/include/linux/dma-mapping.h) + +use crate ::{ + bindings, build_assert, + device::Device , + error::code::*, + error::Result , + transmute::{AsBytes ,FromBytes }, + types::ARef , +}; + +/// Possible attributes associated with a DMA mapping. +/// +/// They can be combined with the operators `|`, `&`, and `!`. +/// +/// Values can be used from the [`attrs`] module. +#[derive( Clone , Copy , PartialEq )] +#[repr(transparent)] +pub struct Attrs (u32 ); + +impl Attrs { +/// Get the raw representation of this attribute. +pub (crate )fn as_raw (self) ->crate ::ffi::c_ulong { + self.0 as _ + } + +/// Check whether `flags` is contained in `self`. +pub fn contains (self, flags:Attrs ) ->bool { + (self & flags) == flags + } +} + +impl core::ops::BitOr for Attrs { +type Output =Self ; +fn bitor (self, rhs:Self ) ->Self ::Output { +Self (self.0 | rhs.0 ) + } +} + +impl core::ops::BitAnd for Attrs { +type Output =Self ; +fn bitand (self, rhs:Self ) ->Self ::Output { +Self (self.0 & rhs.0 ) + } +} + +impl core::ops::Not for Attrs { +type Output =Self ; +fn not (self) ->Self ::Output { +Self (!self.0 ) + } +} + +/// DMA mapping attrributes. +pub mod attrs { +use super ::Attrs ; + +/// Specifies that reads and writes to the mapping may be weakly ordered, that is that reads +/// and writes may pass each other. +pub const DMA_ATTR_WEAK_ORDERING :Attrs =Attrs (bindings::DMA_ATTR_WEAK_ORDERING ); + +/// Specifies that writes to the mapping may be buffered to improve performance. +pub const DMA_ATTR_WRITE_COMBINE :Attrs =Attrs (bindings::DMA_ATTR_WRITE_COMBINE ); + +/// Lets the platform to avoid creating a kernel virtual mapping for the allocated buffer. +pub const DMA_ATTR_NO_KERNEL_MAPPING :Attrs =Attrs (bindings::DMA_ATTR_NO_KERNEL_MAPPING ); + +/// Allows platform code to skip synchronization of the CPU cache for the given buffer assuming +/// that it has been already transferred to 'device' domain. +pub const DMA_ATTR_SKIP_CPU_SYNC :Attrs =Attrs (bindings::DMA_ATTR_SKIP_CPU_SYNC ); + +/// Forces contiguous allocation of the buffer in physical memory. +pub const DMA_ATTR_FORCE_CONTIGUOUS :Attrs =Attrs (bindings::DMA_ATTR_FORCE_CONTIGUOUS ); + +/// This is a hint to the DMA-mapping subsystem that it's probably not worth the time to try +/// to allocate memory to in a way that gives better TLB efficiency. +pub const DMA_ATTR_ALLOC_SINGLE_PAGES :Attrs =Attrs (bindings::DMA_ATTR_ALLOC_SINGLE_PAGES ); + +/// This tells the DMA-mapping subsystem to suppress allocation failure reports (similarly to +/// __GFP_NOWARN). +pub const DMA_ATTR_NO_WARN :Attrs =Attrs (bindings::DMA_ATTR_NO_WARN ); + +/// Used to indicate that the buffer is fully accessible at an elevated privilege level (and +/// ideally inaccessible or at least read-only at lesser-privileged levels). +pub const DMA_ATTR_PRIVILEGED :Attrs =Attrs (bindings::DMA_ATTR_PRIVILEGED ); +} + +/// An abstraction of the `dma_alloc_coherent` API. +/// +/// This is an abstraction around the `dma_alloc_coherent` API which is used to allocate and map +/// large consistent DMA regions. +/// +/// A [`CoherentAllocation`] instance contains a pointer to the allocated region (in the +/// processor's virtual address space) and the device address which can be given to the device +/// as the DMA address base of the region. The region is released once [`CoherentAllocation`] +/// is dropped. +/// +/// # Invariants +/// +/// For the lifetime of an instance of [`CoherentAllocation`], the cpu address is a valid pointer +/// to an allocated region of consistent memory and we hold a reference to the device. +pub struct CoherentAllocation <T :AsBytes +FromBytes > { + dev:ARef <Device >, + dma_handle: bindings::dma_addr_t , + count:usize , + cpu_addr: *mut T , + dma_attrs:Attrs , +} + +impl <T :AsBytes +FromBytes >CoherentAllocation <T > { +/// Allocates a region of `size_of::<T> * count` of consistent memory. +/// +/// # Examples +/// +/// ``` +/// use kernel::device::Device; +/// use kernel::dma::{attrs::*, CoherentAllocation}; +/// +/// # fn test(dev: &Device) -> Result { +/// let c: CoherentAllocation<u64> = CoherentAllocation::alloc_attrs(dev.into(), 4, GFP_KERNEL, +/// DMA_ATTR_NO_WARN)?; +/// # Ok::<(), Error>(()) } +/// ``` +pub fn alloc_attrs ( + dev:ARef <Device >, + count:usize , + gfp_flags: kernel::alloc::Flags , + dma_attrs:Attrs , + ) ->Result <CoherentAllocation <T >> { +build_assert! ( + core::mem::size_of ::<T >() >0 , +"It doesn't make sense for the allocated type to be a ZST" + ); + +let size = count + .checked_mul (core::mem::size_of ::<T >()) + .ok_or (EOVERFLOW )?; +let mut dma_handle =0 ; +// SAFETY: device pointer is guaranteed as valid by invariant on `Device`. +// We ensure that we catch the failure on this function and throw an ENOMEM +let ret =unsafe { + bindings::dma_alloc_attrs ( + dev.as_raw (), + size, + &mut dma_handle, + gfp_flags.as_raw (), + dma_attrs.as_raw (), + ) + }; +if ret.is_null () { +return Err (ENOMEM ); + } +// INVARIANT: We just successfully allocated a coherent region which is accessible for +// `count` elements, hence the cpu address is valid. We also hold a refcounted reference +// to the device. +Ok (Self { + dev, + dma_handle, + count, + cpu_addr: retas *mut T , + dma_attrs, + }) + } + +/// Performs the same functionality as `alloc_attrs`, except the `dma_attrs` is 0 by default. +pub fn alloc_coherent ( + dev:ARef <Device >, + count:usize , + gfp_flags: kernel::alloc::Flags , + ) ->Result <CoherentAllocation <T >> { +CoherentAllocation ::alloc_attrs (dev, count, gfp_flags,Attrs (0 )) + } + +/// Returns the device, base address, dma handle, attributes and the size of the +/// allocated region. +/// +/// The caller takes ownership of the returned resources, i.e., will have the responsibility +/// in calling `bindings::dma_free_attrs`. The allocated region is valid as long as +/// the returned device exists. +pub fn into_parts ( + self, + ) -> ( +ARef <Device >, + *mut T , + bindings::dma_addr_t , + crate::ffi::c_ulong,
Quoted 9 lines
rust/kernel/dma.rs line 195
Quoted 5 lines
rust/kernel/dma.rs new file +5
-0+ usize, + ) { +let size = self.count * core::mem::size_of ::<T >(); +let ret = ( + self.dev.clone(),Calling clone here increments the refcount, but you don't want to do that since it leaks a count.
You mean return the raw *mut bindings::device instead of ARef<Device>. Otherwise the compiler complains not being able to move out ARef<Device> because it doesn't implement Copy.
Thanks,
Abdiel
Alice Ryhl
reviewerRe: [PATCH v10 2/3] rust: add dma coherent allocator abstraction.
Quoted 19 lines · Abdiel Janulgue
Quoted 19 lines
Quoted 18 lines
rust/kernel/dma.rs new file +18
-0+/// Returns the device, base address, dma handle, attributes and the size of the +/// allocated region. +/// +/// The caller takes ownership of the returned resources, i.e., will have the responsibility +/// in calling `bindings::dma_free_attrs`. The allocated region is valid as long as +/// the returned device exists. +pub fn into_parts ( + self, + ) -> ( +ARef <Device >, + *mut T , + bindings::dma_addr_t , +crate ::ffi::c_ulong , +usize , + ) { +let size = self.count * core::mem::size_of ::<T >(); +let ret = ( + self.dev.clone(),
Quoted 7 lines
Quoted 3 lines
Calling clone here increments the refcount, but you don't want to do that since it leaks a count.
You mean return the raw *mut
bindings::deviceinstead of ARef<Device>. Otherwise the compiler complains not being able to move out ARef<Device> because it doesn't implement Copy.
What I mean is that you should return an ARef<Device> without incrementing the refcount. I acknowledge that this requires unsafe, but it's the correct semantics and the unsafe is a consequence of using mem::forget.
You can write core::ptr::read(&self.dev).
Alice
Abdiel Janulgue
reviewerPATCH v10 3/3 MAINTAINERS: add entry for Rust dma mapping helpers device driver API
In reply to Abdiel JanulgueAdd an entry for the Rust dma mapping helpers abstractions.
--- MAINTAINERS | 10 ++++++++++ 1 file changed, 10 insertions(+)
MAINTAINERS +10 -0
@@ -6822,6 +6822,16 @@ F: include/linux/dma-mapping.h F: include/linux/swiotlb.h F: kernel/dma/ +DMA MAPPING HELPERS DEVICE DRIVER API [RUST] +M: Abdiel Janulgue <[email protected]> +M: Danilo Krummrich <[email protected]> +R: Daniel Almeida <[email protected]> +L: [email protected] +S: Supported +W: https://rust-for-linux.com +T: git https://github.com/Rust-for-Linux/linux.git rust-next +F: rust/kernel/dma.rs + DMA-BUF HEAPS FRAMEWORK M: Sumit Semwal <[email protected]> R: Benjamin Gaignard <[email protected]>
Signature · 1 line
2.43.0
Re: [PATCH v10 3/3] MAINTAINERS: add entry for Rust dma mapping helpers device driver API
Quoted 3 lines · Abdiel Janulgue
Add an entry for the Rust dma mapping helpers abstractions.
Signed-off-by Abdiel Janulgue <[email protected]>
Re: [PATCH v10 3/3] MAINTAINERS: add entry for Rust dma mapping helpers device driver API
In reply to Abdiel JanulgueQuoted 2 lines · Abdiel Janulgue
Add an entry for the Rust dma mapping helpers abstractions.
Thanks!
Cheers,
Miguel
Re: [PATCH v10 3/3] MAINTAINERS: add entry for Rust dma mapping helpers device driver API
Quoted 2 lines · Miguel Ojeda
Acked-by Miguel Ojeda <[email protected]>
To clarify: in case DMA MAPPING HELPERS decided to pick this initial one.
Cheers,
Miguel