rust: add dma coherent allocator abstraction
Subsystems (4)
Abdiel Janulgue
reviewerv13 cover rust: add dma coherent allocator abstraction
This series adds the rust bindings for the dma coherent allocator which is needed for nova-core[0]. For v13, the biggest change is to move out the as_slice and write helpers for later discussion. The object is also now wrapped in Devres to explicitly tie it to the lifetime of the device[1]. This is tested on a Nvidia GA104 GPU device using PoC code which parses and loads the GSP firmware via DMA.
Changes sinve v12:
- Move out the contentious functions: as_slice, as_slice_mut, and write
for later discussion as a separate patch. Make write unsafe as well.
Remove skip_drop, use volatile r/w for field_read and field_write
(Alice Ryhl, et al.).
- Documentation improvements, use markdown for intra-doc links
(Miguel Ojeda).
- Move dma addressing capabilities to a separate patch within device.rs
(Andreas Hindborg).
- Add a simple driver to excercise the basics of the api (Danilo).
- Link to v12: https://lore.kernel.org/lkml/[email protected]/
Changes since v11:
- Ensure robust handling for potential pointer arithmetic overflows in bounds checking (Petr Tesařík).
- Add dma mask helpers (Daniel Almeida).
- Clarification in the safety aspects of the as_slice/as_slice_mut API, Use ManuallyDrop trait as a replacement for into_parts(), Add dma_read!/dma_write! helper macros (Alice Ryhl).
Changes since v10:
- rename read() to as_slice() (Boqun Feng)
- Do a bitwise copy of ARef<Device> in into_parts() when returning the device reference (Alice Ryhl).
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).
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.
[0] https://lore.kernel.org/lkml/[email protected]/
[1] https://lore.kernel.org/lkml/[email protected]/
Abdiel Janulgue (6):
rust: error: Add EOVERFLOW
rust: add dma coherent allocator abstraction.
rust: device: add dma addressing capabilities
samples: rust: add Rust dma test sample driver
MAINTAINERS: add entry for Rust dma mapping helpers device driver API
rust: dma: add as_slice/write functions for CoherentAllocation
Danilo Krummrich (1):
rust: pci: impl AsMut<Device> for pci::Device
MAINTAINERS | 12 + rust/bindings/bindings_helper.h | 1 + rust/helpers/dma.c | 8 + rust/helpers/helpers.c | 1 + rust/kernel/device.rs | 29 ++ rust/kernel/dma.rs | 464 ++++++++++++++++++++++++++++++++ rust/kernel/error.rs | 1 + rust/kernel/lib.rs | 1 + rust/kernel/pci.rs | 11 + samples/rust/Kconfig | 11 + samples/rust/Makefile | 1 + samples/rust/rust_dma.rs | 104 +++++++ 12 files changed, 644 insertions(+) create mode 100644 rust/helpers/dma.c create mode 100644 rust/kernel/dma.rs create mode 100644 samples/rust/rust_dma.rs
base-commit: 6ad64bf91728502fe8a4d1419c0a3e4fd323f503
Signature · 1 line
2.43.0
Abdiel Janulgue
reviewerPATCH v13 1/7 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 v13 2/7 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.
A CoherentAllocation is wrapped in Devres which basically guarantees that a driver can't make a CoherentAllocation out-live driver unbind. This is needed, since DMA allocations potentially also result in programming of the IOMMU. IOMMU mappings are device resources and hence the device / driver lifecycle needs to be enforced.
--- rust/bindings/bindings_helper.h | 1 + rust/kernel/dma.rs | 378 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 3 files changed, 380 insertions(+) create mode 100644 rust/kernel/dma.rs
rust/bindings/bindings_helper.h +1 -0
@@ -12,6 +12,7 @@#include <linux/blkdev.h> #include <linux/cred.h> #include <linux/device/faux.h> +#include <linux/dma-mapping.h> #include <linux/errname.h> #include <linux/ethtool.h> #include <linux/file.h>
rust/kernel/dma.rs new file +378 -0
378 lines not on this page · raw message
rust/kernel/lib.rs +1 -0
@@ -44,6 +44,7 @@pub mod device;pub mod device_id;pub mod devres; +pub mod dma;pub mod driver;pub mod error;pub mod faux;
Signature · 1 line
2.43.0
Re: [PATCH v13 2/7] rust: add dma coherent allocator abstraction.
Quoted 11 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.
A CoherentAllocation is wrapped in Devres which basically guarantees that a driver can't make a CoherentAllocation out-live driver unbind. This is needed, since DMA allocations potentially also result in programming of the IOMMU. IOMMU mappings are device resources and hence the device / driver lifecycle needs to be enforced.
Signed-off-by Abdiel Janulgue <[email protected]>
You might want to add #[inline] annotations to the various methods, but otherwise LGTM.
rust/kernel/dma.rs line 378
Quoted 11 lines
rust/kernel/dma.rs new file +11
-0+/// Helper function to set the bit mask for DMA addressing. +pub const fn dma_bit_mask (n:usize ) ->u64 { +if n >64 { +return 0 ; + } +if n ==64 { + !0 + }else { + (1 << (n)) -1 + } +}
You don't use this method?
Alice
Andreas Hindborg
reviewerRe: [PATCH v13 2/7] rust: add dma coherent allocator abstraction.
In reply to Abdiel JanulgueQuoted 15 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.
A CoherentAllocation is wrapped in Devres which basically guarantees that a driver can't make a CoherentAllocation out-live driver unbind. This is needed, since DMA allocations potentially also result in programming of the IOMMU. IOMMU mappings are device resources and hence the device / driver lifecycle needs to be enforced.
Signed-off-by Abdiel Janulgue <[email protected]>---
rust/kernel/dma.rs new file +3
-0+ +/// Reads the value of `field` and ensures that its type is [`FromBytes`]. +///
rust/kernel/dma.rs line 244
Quoted 10 lines
rust/kernel/dma.rs new file +10
-0+/// # Safety +/// +/// This must be called from the [`dma_read`] macro which ensures that the `field` pointer is +/// validated beforehand. +/// +/// Public but hidden since it should only be used from [`dma_read`] macro. +#[doc(hidden)] +pub unsafe fn field_read <F :FromBytes >(&self, field: *const F ) ->F { +// SAFETY: By the safety requirements field is valid. +unsafe { field.read_volatile () }
From the docs of read_volatile:
Just like in C, whether an operation is volatile has no bearing whatsoever on questions involving concurrent access from multiple threads. Volatile accesses behave exactly like non-atomic accesses in that regard. In particular, a race between a read_volatile and any write operation to the same location is undefined behavior.
So the safety requirement is not sufficient. Alice responded to my question on v12:
Quoted 1 line
Volatile reads/writes that race are OK?
I will not give a blanket yes to that. If you read their docs, you will find that they claim to not allow it. But they are the correct choice for DMA memory, and there's no way in practice to get miscompilations on memory locations that are only accessed with volatile operations, and never have references to them created.
In general, this will fall into the exception that we've been given from the Rust people. In cases such as this where the Rust language does not give us the operation we want, do it like you do in C. Since Rust uses LLVM which does not miscompile the C part of the kernel, it should not miscompile the Rust part either.
Since we have an exception for the safety requirements in the documentation, we should make that clear in the safety comment at the call site.
Best regards,
Andreas Hindborg
Re: [PATCH v13 2/7] rust: add dma coherent allocator abstraction.
In reply to Abdiel Janulguerust/kernel/dma.rs line 167
Quoted 9 lines · Abdiel Janulgue
rust/kernel/dma.rs new file +9
-0+// SAFETY: Device pointer is guaranteed as valid by the type invariant on `Device`. +let ret =unsafe { + bindings::dma_alloc_attrs ( + dev.as_raw (), + size, + &mut dma_handle, + gfp_flags.as_raw (), + dma_attrs.as_raw (), + )
This is not the correct safety statement, the device must have a driver bound to call this function, a struct device reference is not sufficient.
I belive Danilo was suggesting to ignore this unsafety for now, but if so it should be documented correctly.
Also think the use of devres here is going to be very problematic for drivers to use as I said in other emails. :(
Jason
Danilo Krummrich
maintainerRe: [PATCH v13 2/7] rust: add dma coherent allocator abstraction.
Quoted 12 lines · Jason Gunthorpe
rust/kernel/dma.rs line 167
Quoted 9 lines · Abdiel Janulgue
rust/kernel/dma.rs new file +9
-0+// SAFETY: Device pointer is guaranteed as valid by the type invariant on `Device`. +let ret =unsafe { + bindings::dma_alloc_attrs ( + dev.as_raw (), + size, + &mut dma_handle, + gfp_flags.as_raw (), + dma_attrs.as_raw (), + )
Quoted 6 lines
This is not the correct safety statement, the device must have a driver bound to call this function, a struct device reference is not sufficient.
I belive Danilo was suggesting to ignore this unsafety for now, but if so it should be documented correctly.
If just landed patches [1], which are the foundation of addressing this issue.
With the next cycle, this will be ensured by the type system.
Quoted 3 lines
Also think the use of devres here is going to be very problematic for drivers to use as I said in other emails. :(
In an earlier reply today in a different thread already gave you the link [2] of what we landed, which, besides explaining the situation, also makes clear that there is *no* Devres wrapper around a CoherentAllocation and why.
[1] https://lore.kernel.org/lkml/[email protected]/
[2] https://github.com/Rust-for-Linux/linux/blob/rust-next/rust/kernel/dma.rs#L120
Re: [PATCH v13 2/7] rust: add dma coherent allocator abstraction.
Quoted 13 lines · Danilo Krummrich
Quoted 12 lines · Jason Gunthorpe
Quoted 9 lines · Abdiel Janulgue
rust/kernel/dma.rs new file +9
-0+// SAFETY: Device pointer is guaranteed as valid by the type invariant on `Device`. +let ret =unsafe { + bindings::dma_alloc_attrs ( + dev.as_raw (), + size, + &mut dma_handle, + gfp_flags.as_raw (), + dma_attrs.as_raw (), + )
Quoted 8 lines
Quoted 6 lines
This is not the correct safety statement, the device must have a driver bound to call this function, a struct device reference is not sufficient.
I belive Danilo was suggesting to ignore this unsafety for now, but if so it should be documented correctly.
If just landed patches [1], which are the foundation of addressing this issue.
Those patches say:
The context types can be extended as required, e.g. to limit availability of certain (bus) device functions to probe().
Which is not an appropriate limitation for dma_alloc_coherent, we expect it to be called outside probe in real drivers. Is there more to that story?
Regardless, the safety comment should not be merged with incorrect information. :\
Quoted 6 lines
Quoted 2 lines
Also think the use of devres here is going to be very problematic for drivers to use as I said in other emails. :(
In an earlier reply today in a different thread already gave you the link [2] of what we landed, which, besides explaining the situation, also makes clear that there is *no* Devres wrapper around a CoherentAllocation and why.
Yes, I see, I have so much email right now it is hard find all the different versions of everything.
Jason
Danilo Krummrich
maintainerRe: [PATCH v13 2/7] rust: add dma coherent allocator abstraction.
Quoted 23 lines · Jason Gunthorpe
Quoted 13 lines · Danilo Krummrich
Quoted 12 lines · Jason Gunthorpe
Quoted 9 lines · Abdiel Janulgue
rust/kernel/dma.rs new file +9
-0+// SAFETY: Device pointer is guaranteed as valid by the type invariant on `Device`. +let ret =unsafe { + bindings::dma_alloc_attrs ( + dev.as_raw (), + size, + &mut dma_handle, + gfp_flags.as_raw (), + dma_attrs.as_raw (), + )Quoted 8 lines
Quoted 6 lines
This is not the correct safety statement, the device must have a driver bound to call this function, a struct device reference is not sufficient.
I belive Danilo was suggesting to ignore this unsafety for now, but if so it should be documented correctly.
If just landed patches [1], which are the foundation of addressing this issue.
Quoted 8 lines
Those patches say:
The context types can be extended as required, e.g. to limit availability of certain (bus) device functions to
probe().Which is not an appropriate limitation for
dma_alloc_coherent, we expect it to be called outside probe in real drivers. Is there more to that story?
Yeah, we can also use them to derive specifically typed Device instances from other entry points of the driver where we know for sure that at this point the device must (still) be bound to the driver.
For instance, bus callbacks, subsystem callbacks, certain (but not all) IOCTLs, IRQ handlers, etc.
All those cases can be covered by only the type system, without additional locks. We could even use this as an optimization to bypass Devres' try_access() calls when holding a corresponding device instance in those places.
Quoted 3 lines
Regardless, the safety comment should not be merged with incorrect information. :\
v15 did land in rust-next, so unfortunately this was overlooked. Since you caught, mind sending a patch improving the comment?
Abdiel Janulgue
reviewerPATCH v13 3/7 rust: pci: impl AsMut<Device> for pci::Device
In reply to Abdiel JanulgueFrom: Danilo Krummrich <[email protected]>
Some device methods require mutable references, since they change the underlying struct device without lock protection.
Hence, make it possible to retrieve a mutable reference to a Device from a mutable pci::Device.
--- rust/kernel/pci.rs | 11 +++++++++++ 1 file changed, 11 insertions(+)
rust/kernel/pci.rs +11 -0
@@ -432,3 +432,14 @@ fn as_ref(&self) -> &device::Device { &self.0 } } + +impl AsMut <device::Device >for Device { +fn as_mut (&mut self) -> &mut device::Device { +// SAFETY: +// - `self.0.as_raw()` is valid by the type invariant of `device::Device`, +// - `struct device` is embedded in `struct pci_dev`, hence it is safe to give out a +// mutable reference for `device::Device` if we have a mutable reference to the +// corresponding `pci::Device`. +unsafe { &mut *self.0 .as_raw ().cast () } + } +}
Signature · 1 line
2.43.0
Alice Ryhl
reviewerRe: [PATCH v13 3/7] rust: pci: impl AsMut<Device> for pci::Device
Quoted 22 lines · Abdiel Janulgue
From: Danilo Krummrich <[email protected]>
Some device methods require mutable references, since they change the underlying struct device without lock protection.
Hence, make it possible to retrieve a mutable reference to a Device from a mutable
pci::Device.Signed-off-by Danilo Krummrich <[email protected]>--- rust/kernel/pci.rs | 11 +++++++++++ 1 file changed, 11 insertions(+)rust/kernel/pci.rs +1
-0@@ -432,3 +432,14 @@ fn as_ref(&self) -> &device::Device { &self.0 } } +
rust/kernel/pci.rs fn as_ref(&self) -> &device::Device { · line 445
Quoted 10 lines
rust/kernel/pci.rs +10
-0+impl AsMut <device::Device >for Device { +fn as_mut (&mut self) -> &mut device::Device { +// SAFETY: +// - `self.0.as_raw()` is valid by the type invariant of `device::Device`, +// - `struct device` is embedded in `struct pci_dev`, hence it is safe to give out a +// mutable reference for `device::Device` if we have a mutable reference to the +// corresponding `pci::Device`. +unsafe { &mut *self.0 .as_raw ().cast () } + } +}
This makes it possible to call mem::swap on two devices, which I doubt is allowed.
Alice
Danilo Krummrich
maintainerRe: [PATCH v13 3/7] rust: pci: impl AsMut<Device> for pci::Device
Quoted 28 lines · Alice Ryhl
Quoted 27 lines · Abdiel Janulgue
From: Danilo Krummrich <[email protected]>
Some device methods require mutable references, since they change the underlying struct device without lock protection.
Hence, make it possible to retrieve a mutable reference to a Device from a mutable
pci::Device.Signed-off-by Danilo Krummrich <[email protected]>--- rust/kernel/pci.rs | 11 +++++++++++ 1 file changed, 11 insertions(+)rust/kernel/pci.rs +6
-0@@ -432,3 +432,14 @@ fn as_ref(&self) -> &device::Device { &self.0 } } + +impl AsMut <device::Device >for Device { +fn as_mut (&mut self) -> &mut device::Device { +// SAFETY: +// - `self.0.as_raw()` is valid by the type invariant of `device::Device`, +// - `struct device` is embedded in `struct pci_dev`, hence it is safe to give out a
Quoted 8 lines
rust/kernel/pci.rs fn as_ref(&self) -> &device::Device { · line 445
Quoted 5 lines
rust/kernel/pci.rs +5
-0+// mutable reference for `device::Device` if we have a mutable reference to the +// corresponding `pci::Device`. +unsafe { &mut *self.0 .as_raw ().cast () } + } +}This makes it possible to call
mem::swapon two devices, which I doubt is allowed.
Good catch, that's of course not allowed.
Obviously, this is for Device::dma_set_mask(), introduced in a subsequent patch.
Thinking about it, maybe it should be implemented by bus devices instead (e.g. pci::Device) -- dma_set_mask() doesn't make sense for every device.
Greg KH
maintainerRe: [PATCH v13 3/7] rust: pci: impl AsMut<Device> for pci::Device
In reply to Abdiel JanulgueQuoted 10 lines · Abdiel Janulgue
From: Danilo Krummrich <[email protected]>
Some device methods require mutable references, since they change the underlying struct device without lock protection.
Hence, make it possible to retrieve a mutable reference to a Device from a mutable
pci::Device.Signed-off-by Danilo Krummrich <[email protected]>---
Note, you can't forward on a patch from someone else without also signing off on it. Please read the DCO for what this means and why.
thanks,
greg k-h
Abdiel Janulgue
reviewerRe: [PATCH v13 3/7] rust: pci: impl AsMut<Device> for pci::Device
Quoted 6 lines · Greg KH
Quoted 5 lines · Abdiel Janulgue
From: Danilo Krummrich <[email protected]>
Some device methods require mutable references, since they change the underlying struct device without lock protection.
Quoted 9 lines
Quoted 5 lines
Hence, make it possible to retrieve a mutable reference to a Device from a mutable
pci::Device.Signed-off-by Danilo Krummrich <[email protected]>---
Note, you can't forward on a patch from someone else without also signing off on it. Please read the DCO for what this means and why.
Thanks for the reminder! Will do so in next revision.
Regards,
Abdiel
Abdiel Janulgue
reviewerPATCH v13 4/7 rust: device: add dma addressing capabilities
In reply to Abdiel JanulgueAdd functions to set the DMA mask to inform the kernel about the device's DMA addressing capabilities.
--- rust/helpers/dma.c | 8 ++++++++ rust/helpers/helpers.c | 1 + rust/kernel/device.rs | 29 +++++++++++++++++++++++++++++ 3 files changed, 38 insertions(+) create mode 100644 rust/helpers/dma.c
rust/helpers/dma.c new file +8 -0
@@ -0,0 +1,8 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include <linux/dma-mapping.h> + +int rust_helper_dma_set_mask_and_coherent (struct device *dev,u64 mask) +{ +return dma_set_mask_and_coherent (dev, mask); +}
rust/helpers/helpers.c +1 -0
@@ -13,6 +13,7 @@#include "build_bug.c" #include "cred.c" #include "device.c" +#include "dma.c" #include "err.c" #include "fs.c" #include "io.c"
rust/kernel/device.rs +29 -0
@@ -6,10 +6,12 @@use crate ::{ bindings, + error::Result , str::CStr , types::{ARef ,Opaque }, };use core::{fmt, ptr}; +use kernel::prelude::*;#[cfg( CONFIG_PRINTK )] use crate ::c_str;
@@ -187,6 +189,33 @@ pub fn property_present(&self, name: &CStr) -> bool {// SAFETY: By the invariant of `CStr`, `name` is null-terminated. unsafe { bindings::device_property_present (self.as_raw ().cast_const (), name.as_char_ptr ()) } } + +/// Inform the kernel about the device's DMA addressing capabilities. +/// +/// Set both the DMA mask and the coherent DMA mask to the same thing. +/// Note that we don't check the return value from the C `dma_set_coherent_mask` +/// as the DMA API guarantees that the coherent DMA mask can be set to +/// the same or smaller than the streaming DMA mask. +pub fn dma_set_mask_and_coherent (&mut self, mask:u64 ) ->Result { +// SAFETY: device pointer is guaranteed as valid by invariant on `Device`. +let ret =unsafe { bindings::dma_set_mask_and_coherent (self.as_raw (), mask) }; +if ret !=0 { +Err (Error ::from_errno (ret)) + }else { +Ok (()) + } + } + +/// Same as [`dma_set_mask_and_coherent`], but set the mask only for streaming mappings. +pub fn dma_set_mask (&mut self, mask:u64 ) ->Result { +// SAFETY: device pointer is guaranteed as valid by invariant on `Device`. +let ret =unsafe { bindings::dma_set_mask (self.as_raw (), mask) }; +if ret !=0 { +Err (Error ::from_errno (ret)) + }else { +Ok (()) + } + } }// SAFETY: Instances of `Device` are always reference-counted.
Signature · 1 line
2.43.0
Andreas Hindborg
reviewerRe: [PATCH v13 4/7] rust: device: add dma addressing capabilities
Quoted 64 lines · Abdiel Janulgue
Add functions to set the DMA mask to inform the kernel about the device's DMA addressing capabilities.
Signed-off-by Abdiel Janulgue <[email protected]>--- rust/helpers/dma.c | 8 ++++++++ rust/helpers/helpers.c | 1 + rust/kernel/device.rs | 29 +++++++++++++++++++++++++++++ 3 files changed, 38 insertions(+) create mode 100644 rust/helpers/dma.crust/helpers/dma.c new file +8
-0@@ -0,0 +1,8 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include <linux/dma-mapping.h> + +int rust_helper_dma_set_mask_and_coherent (struct device *dev,u64 mask) +{ +return dma_set_mask_and_coherent (dev, mask); +}rust/helpers/helpers.c +1
-0@@ -13,6 +13,7 @@#include "build_bug.c" #include "cred.c" #include "device.c" +#include "dma.c" #include "err.c" #include "fs.c" #include "io.c" rust/kernel/device.rs +8
-0@@ -6,10 +6,12 @@use crate ::{ bindings, + error::Result , str::CStr , types::{ARef ,Opaque }, };use core::{fmt, ptr}; +use kernel::prelude::*;#[cfg( CONFIG_PRINTK )] use crate ::c_str;@@ -187,6 +189,33 @@ pub fn property_present(&self, name: &CStr) -> bool {// SAFETY: By the invariant of `CStr`, `name` is null-terminated. unsafe { bindings::device_property_present (self.as_raw ().cast_const (), name.as_char_ptr ()) } } + +/// Inform the kernel about the device's DMA addressing capabilities. +/// +/// Set both the DMA mask and the coherent DMA mask to the same thing. +/// Note that we don't check the return value from the C `dma_set_coherent_mask` +/// as the DMA API guarantees that the coherent DMA mask can be set to
rust/kernel/device.rs pub fn property_present(&self, name: &CStr) -> bool { · line 207
Quoted 10 lines
rust/kernel/device.rs +10
-0+/// the same or smaller than the streaming DMA mask. +pub fn dma_set_mask_and_coherent (&mut self, mask:u64 ) ->Result { +// SAFETY: device pointer is guaranteed as valid by invariant on `Device`. +let ret =unsafe { bindings::dma_set_mask_and_coherent (self.as_raw (), mask) }; +if ret !=0 { +Err (Error ::from_errno (ret)) + }else { +Ok (()) + } + }
I think we can use Error::from_errno here (and below). As far as I can tell, these C functions return negative on error.
Quoted 4 lines
rust/kernel/device.rs +4
-0+ +/// Same as [`dma_set_mask_and_coherent`], but set the mask only for streaming mappings. +pub fn dma_set_mask (&mut self, mask:u64 ) ->Result { +// SAFETY: device pointer is guaranteed as valid by invariant on `Device`.
rust/kernel/device.rs pub fn property_present(&self, name: &CStr) -> bool { · line 221
Quoted 10 lines
rust/kernel/device.rs +7
-0+let ret =unsafe { bindings::dma_set_mask (self.as_raw (), mask) }; +if ret !=0 { +Err (Error ::from_errno (ret)) + }else { +Ok (()) + } + } }// SAFETY: Instances of `Device` are always reference-counted.
Best regards,
Andreas Hindborg
Abdiel Janulgue
reviewerRe: [PATCH v13 4/7] rust: device: add dma addressing capabilities
Hi,
Quoted 71 lines · Andreas Hindborg
Quoted 69 lines · Abdiel Janulgue
Add functions to set the DMA mask to inform the kernel about the device's DMA addressing capabilities.
Signed-off-by Abdiel Janulgue <[email protected]>--- rust/helpers/dma.c | 8 ++++++++ rust/helpers/helpers.c | 1 + rust/kernel/device.rs | 29 +++++++++++++++++++++++++++++ 3 files changed, 38 insertions(+)create mode 100644
rust/helpers/dma.crust/helpers/dma.c new file +8
-0@@ -0,0 +1,8 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include <linux/dma-mapping.h> + +int rust_helper_dma_set_mask_and_coherent (struct device *dev,u64 mask) +{ +return dma_set_mask_and_coherent (dev, mask); +}rust/helpers/helpers.c +1
-0@@ -13,6 +13,7 @@#include "build_bug.c" #include "cred.c" #include "device.c" +#include "dma.c" #include "err.c" #include "fs.c" #include "io.c" rust/kernel/device.rs +13
-0@@ -6,10 +6,12 @@use crate ::{ bindings, + error::Result , str::CStr , types::{ARef ,Opaque }, };use core::{fmt, ptr}; +use kernel::prelude::*;#[cfg( CONFIG_PRINTK )] use crate ::c_str;@@ -187,6 +189,33 @@ pub fn property_present(&self, name: &CStr) -> bool {// SAFETY: By the invariant of `CStr`, `name` is null-terminated. unsafe { bindings::device_property_present (self.as_raw ().cast_const (), name.as_char_ptr ()) } } + +/// Inform the kernel about the device's DMA addressing capabilities. +/// +/// Set both the DMA mask and the coherent DMA mask to the same thing. +/// Note that we don't check the return value from the C `dma_set_coherent_mask` +/// as the DMA API guarantees that the coherent DMA mask can be set to +/// the same or smaller than the streaming DMA mask. +pub fn dma_set_mask_and_coherent (&mut self, mask:u64 ) ->Result { +// SAFETY: device pointer is guaranteed as valid by invariant on `Device`. +let ret =unsafe { bindings::dma_set_mask_and_coherent (self.as_raw (), mask) }; +if ret !=0 {
Quoted 8 lines
rust/kernel/device.rs pub fn property_present(&self, name: &CStr) -> bool { · line 207
Quoted 5 lines
rust/kernel/device.rs +5
-0+Err (Error ::from_errno (ret)) + }else { +Ok (()) + } + }I think we can use
Error::from_errnohere (and below). As far as I can tell, these C functions return negative on error.
This already uses Error::from_errno?
Thanks!
Quoted 21 lines
Quoted 5 lines
rust/kernel/device.rs +4
-0+ +/// Same as [`dma_set_mask_and_coherent`], but set the mask only for streaming mappings. +pub fn dma_set_mask (&mut self, mask:u64 ) ->Result { +// SAFETY: device pointer is guaranteed as valid by invariant on `Device`. rust/kernel/device.rs pub fn property_present(&self, name: &CStr) -> bool { · line 221
Quoted 10 lines
rust/kernel/device.rs +7
-0+let ret =unsafe { bindings::dma_set_mask (self.as_raw (), mask) }; +if ret !=0 { +Err (Error ::from_errno (ret)) + }else { +Ok (()) + } + } }// SAFETY: Instances of `Device` are always reference-counted. Best regards,
Andreas Hindborg
Re: [PATCH v13 4/7] rust: device: add dma addressing capabilities
Quoted 2 lines · Abdiel Janulgue
This already uses
Error::from_errno?
Maybe Andreas meant to_result?
Cheers,
Miguel
Andreas Hindborg
reviewerRe: [PATCH v13 4/7] rust: device: add dma addressing capabilities
Quoted 6 lines · Miguel Ojeda
Quoted 2 lines · Abdiel Janulgue
This already uses
Error::from_errno?Maybe Andreas meant
to_result?
Yes, sorry. It includes the if/else, but it tests for ret < 0. But I think that is fine here.
Best regards,
Andreas Hindborg
Abdiel Janulgue
reviewerPATCH v13 5/7 samples: rust: add Rust dma test sample driver
In reply to Abdiel JanulgueAdd a simple driver to excercise the basics of the Rust DMA coherent allocator bindings.
--- samples/rust/Kconfig | 11 +++++ samples/rust/Makefile | 1 + samples/rust/rust_dma.rs | 104 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 116 insertions(+) create mode 100644 samples/rust/rust_dma.rs
samples/rust/Kconfig +11 -0
@@ -78,4 +78,15 @@ config SAMPLE_RUST_HOSTPROGS If unsure, say N. +config SAMPLE_RUST_DRIVER_DMA + tristate "DMA test driver" + depends on PCI + help + This option builds the Rust dma test driver sample. + + To compile this as a module, choose M here: + the module will be called dma. + + If unsure, say N. + endif # SAMPLES_RUST
samples/rust/Makefile +1 -0
@@ -7,6 +7,7 @@ obj-$(CONFIG_SAMPLE_RUST_PRINT) += rust_print.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI) += rust_driver_pci.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM) += rust_driver_platform.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_FAUX) += rust_driver_faux.o +obj-$(CONFIG_SAMPLE_RUST_DRIVER_DMA) += rust_dma.o rust_print-y := rust_print_main.o rust_print_events.o
samples/rust/rust_dma.rs new file +104 -0
104 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH v13 6/7 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 | 12 ++++++++++++ 1 file changed, 12 insertions(+)
MAINTAINERS +12 -0
@@ -6902,6 +6902,18 @@ 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]> +R: Robin Murphy <[email protected]> +R: Andreas Hindborg <[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
Abdiel Janulgue
reviewerPATCH v13 7/7 rust: dma: add as_slice/write functions for CoherentAllocation
In reply to Abdiel JanulgueAdd unsafe accessors for the region for reading or writing large blocks of data.
--- rust/kernel/dma.rs | 86 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+)
rust/kernel/dma.rs +86 -0
@@ -213,6 +213,92 @@ pub fn dma_handle(&self) -> bindings::dma_addr_t { self.dma_handle } +/// Returns the data from the region starting from `offset` as a slice. +/// `offset` and `count` are in units of `T`, not the number of bytes. +/// +/// Due to the safety requirements of slice, the caller should consider that the region could +/// be modified by the device at anytime. For ringbuffer type of r/w access or use-cases where +/// the pointer to the live data is needed, `start_ptr()` or `start_ptr_mut()` could be +/// used instead. +/// +/// # Safety +/// +/// * Callers must ensure that no hardware operations that involve the buffer are currently +/// taking place while the returned slice is live. +/// * Callers must ensure that this call does not race with a write to the same region while +/// while the returned slice is live. +pub unsafe fn as_slice (&self, offset:usize , count:usize ) ->Result <&[T ]> { +let end = offset.checked_add (count).ok_or (EOVERFLOW )?; +if end >= self.count { +return Err (EINVAL ); + } +// SAFETY: +// - The pointer is valid due to type invariant on `CoherentAllocation`, +// we've just checked that the range and index is within bounds. The immutability of the +// of data is also guaranteed by the safety requirements of the function. +// - `offset` can't overflow since it is smaller than `self.count` and we've checked +// that `self.count` won't overflow early in the constructor. +Ok (unsafe { core::slice::from_raw_parts (self.cpu_addr.add (offset), count) }) + } + +/// Performs the same functionality as [`as_slice`], except that a mutable slice is returned. +/// +/// # Safety +/// +/// * Callers must ensure that no hardware operations that involve the buffer are currently +/// taking place while the returned slice is live. +/// * Callers must ensure that this call does not race with a read or write to the same region +/// while the returned slice is live. +pub unsafe fn as_slice_mut (&self, offset:usize , count:usize ) ->Result <&mut [T ]> { +let end = offset.checked_add (count).ok_or (EOVERFLOW )?; +if end >= self.count { +return Err (EINVAL ); + } +// SAFETY: +// - The pointer is valid due to type invariant on `CoherentAllocation`, +// we've just checked that the range and index is within bounds. The immutability of the +// of data is also guaranteed by the safety requirements of the function. +// - `offset` can't overflow since it is smaller than `self.count` and we've checked +// that `self.count` won't overflow early in the constructor. +Ok (unsafe { core::slice::from_raw_parts_mut (self.cpu_addr.add (offset), count) }) + } + +/// Writes data to the region starting from `offset`. `offset` is in units of `T`, not the +/// number of bytes. +/// +/// # Safety +/// +/// * Callers must ensure that no hardware operations that involve the buffer overlaps with +/// this write. +/// * Callers must ensure that this call does not race with a read or write to the same region +/// that overlaps with this write. +/// +/// # Examples +/// +/// ``` +/// # fn test(alloc: &mut kernel::dma::CoherentAllocation<u8>) -> Result { +/// let somedata: [u8; 4] = [0xf; 4]; +/// let buf: &[u8] = &somedata; +/// // SAFETY: No hw operation on the device and no other r/w access to the region at this point. +/// unsafe { alloc.write(buf, 0)?; } +/// # Ok::<(), Error>(()) } +/// ``` +pub unsafe fn write (&self, src: &[T ], offset:usize ) ->Result { +let end = offset.checked_add (src.len ()).ok_or (EOVERFLOW )?; +if end >= self.count { +return Err (EINVAL ); + } +// SAFETY: +// - The pointer is valid due to type invariant on `CoherentAllocation` +// and we've just checked that the range and index is within bounds. +// - `offset` can't overflow since it is smaller than `self.count` and we've checked +// that `self.count` won't overflow early in the constructor. +unsafe { + core::ptr::copy_nonoverlapping (src.as_ptr (), self.cpu_addr.add (offset), src.len ()) + }; +Ok (()) + } +/// Returns a pointer to an element from the region with bounds checking. `offset` is in /// units of `T`, not the number of bytes. ///
Signature · 1 line
2.43.0
Danilo Krummrich
maintainerQuoted 5 lines · Abdiel Janulgue
This series adds the rust bindings for the dma coherent allocator which is needed for nova-core[0]. For v13, the biggest change is to move out the
as_sliceand write helpers for later discussion. The object is also now wrapped in Devres to explicitly tie it to the lifetime of the device[1].
Just to clarify:
What is meant here is that a CoherentAllocation can't out-live driver unbind. This is not equivalent to the lifetime of the corresponding struct device.