Skip to contentSkip to conversation

rust: add dma coherent allocator abstraction

PATCH In review Abdiel Janulgue 6 participants 23 messages Mar 17, 2025 – Jun 3, 2025

Subsystems (4)
lore
Share & tools
lore

Abdiel Janulgue

author reviewer
#0 lore raw

v15 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 v15, document safety comments on the exception of usage on read_volatile and write_volatile as suggested by Boqun Feng.

This is tested on a Nvidia GA104 GPU device using PoC code which parses and loads the GSP firmware via DMA.

Changes since v14:
- Add safety comments on the exception of usage on read_volatile
and write_volatile (Boqun Feng, Benno Lossin, Andreas Hindborg).
- Link to v14: https://lore.kernel.org/lkml/[email protected]/

Changes since v13:
- Remove Devres wrapper, document correct solution for proper resource deallocation as TODO, add patches from Danilo to properly add DMA addressing capabilities for the device which requires a new trait that defines the DMA specific methods of devices. (Danilo)

Changes since 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).

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]/

Abdiel Janulgue (5):
rust: error: Add EOVERFLOW
rust: add dma coherent allocator abstraction.
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 (6):
rust: dma: implement dma::Device trait
rust: dma: add dma addressing capabilities
rust: pci: implement the dma::Device trait
rust: platform: implement the dma::Device trait
rust: dma: use dma::Device in CoherentAllocation
rust: samples: dma: set DMA mask

 MAINTAINERS                     |  13 +
 rust/bindings/bindings_helper.h |   1 +
 rust/helpers/dma.c              |   8 +
 rust/helpers/helpers.c          |   1 +
 rust/kernel/dma.rs              | 521 ++++++++++++++++++++++++++++++++
 rust/kernel/error.rs            |   1 +
 rust/kernel/lib.rs              |   1 +
 rust/kernel/pci.rs              |   2 +
 rust/kernel/platform.rs         |   2 +
 samples/rust/Kconfig            |  11 +
 samples/rust/Makefile           |   1 +
 samples/rust/rust_dma.rs        | 104 +++++++
 12 files changed, 666 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: cf25bc61f8aecad9b0c45fe32697e35ea4b13378

Signature · 1 line
2.43.0
author reviewer
#1 lore raw

PATCH v15 1/11 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
index 376f6a6ae5e3..30014d507ed3 100644
@@ -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
author reviewer
#2 lore raw

PATCH v15 2/11 rust: add dma coherent allocator abstraction.

In reply to 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.

---
 rust/bindings/bindings_helper.h |   1 +
 rust/kernel/dma.rs              | 387 ++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs              |   1 +
 3 files changed, 389 insertions(+)
 create mode 100644 rust/kernel/dma.rs
rust/bindings/bindings_helper.h +1 -0
index ae39fc18a8bf..ccb988340df6 100644
@@ -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 +387 -0

387 lines not on this page · raw message

rust/kernel/lib.rs +1 -0
index c92497c7c655..001374a96d66 100644
@@ -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
#3 lore raw

Re: [PATCH v15 02/11] rust: add dma coherent allocator abstraction.

"Abdiel Janulgue" <[email protected]> writes:

[...]

Quoted 17 lines
rust/kernel/dma.rs new file +17 -0
+/// Possible attributes associated with a DMA mapping.
+///
+/// They can be combined with the operators `|`, `&`, and `!`.
+///
+/// Values can be used from the [`attrs`] module.
+///
+/// # Examples
+///
+/// ```
+/// use kernel::device::Device;
+/// use kernel::dma::{attrs::*, CoherentAllocation};
+///
+/// # fn test(dev: &Device) -> Result {
+/// let attribs = DMA_ATTR_FORCE_CONTIGUOUS | DMA_ATTR_NO_WARN;
+/// let c: CoherentAllocation<u64> =
+///     CoherentAllocation::alloc_attrs(dev, 4, GFP_KERNEL, attribs)?;
+/// # Ok::<(), Error>(()) }

rust/kernel/dma.rs line 42

Quoted 10 lines
rust/kernel/dma.rs new file +10 -0
+/// ```
+#[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 _
+    }

OT: I wonder why we do not have usize: From<u32>? It seems like this should be fine, even on 32 bit systems?

Quoted 41 lines
rust/kernel/dma.rs new file +41 -0
+
+    /// 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 attributes.
+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);

rust/kernel/dma.rs line 93

Quoted 10 lines
rust/kernel/dma.rs new file +10 -0
+
+    /// 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.

The wording of in the other doc comments is different than this one and the two next ones. Consider aligning them:

Hints the DMA-mapping subsystem that ...

rust/kernel/dma.rs line 97

Quoted 4 lines
rust/kernel/dma.rs new file +4 -0
+    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).

Tells the DMA-mapping subsystem ...

rust/kernel/dma.rs line 101

Quoted 4 lines
rust/kernel/dma.rs new file +4 -0
+    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).

Indicates that the buffer ...

rust/kernel/dma.rs line 108

Quoted 7 lines
rust/kernel/dma.rs new file +7 -0
+    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.

I think it would be nice to have a description of what a coherent DMA region is here. From Documentation/core-api/dma-api.rst:

Consistent memory is memory for which a write by either the device or the processor can immediately be read by the processor or device without having to worry about caching effects. (You may however need to make sure to flush the processor's write buffers before telling devices to read that memory.)

I think consistent and coherent are used interchangeably in the kernel. If so, can we settle on just one of the terms in the rust code?

Quoted 13 lines
rust/kernel/dma.rs new file +13 -0
+///
+/// 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_addr` is a valid pointer
+/// to an allocated region of consistent memory and `dma_handle` is the DMA address base of
+/// the region.
+// TODO
+//

rust/kernel/dma.rs line 131

Quoted 10 lines
rust/kernel/dma.rs new file +10 -0
+// DMA allocations potentially carry device resources (e.g.IOMMU mappings), hence for soundness
+// reasons DMA allocation would need to be embedded in a `Devres` container, in order to ensure
+// that device resources can never survive device unbind.
+//
+// However, it is neither desirable nor necessary to protect the allocated memory of the DMA
+// allocation from surviving device unbind; it would require RCU read side critical sections to
+// access the memory, which may require subsequent unnecessary copies.
+//
+// Hence, find a way to revoke the device resources of a `CoherentAllocation`, but not the
+// entire `CoherentAllocation` including the allocated memory itself.

Looking forward to seeing this solution.

Best regards,
Andreas Hindborg

reviewer
#4 lore raw

Re: [PATCH v15 02/11] rust: add dma coherent allocator abstraction.

Quoted 26 lines · Andreas Hindborg

"Abdiel Janulgue" <[email protected]> writes:

[...]

Quoted 22 lines
rust/kernel/dma.rs new file +22 -0
+/// Possible attributes associated with a DMA mapping.
+///
+/// They can be combined with the operators `|`, `&`, and `!`.
+///
+/// Values can be used from the [`attrs`] module.
+///
+/// # Examples
+///
+/// ```
+/// use kernel::device::Device;
+/// use kernel::dma::{attrs::*, CoherentAllocation};
+///
+/// # fn test(dev: &Device) -> Result {
+/// let attribs = DMA_ATTR_FORCE_CONTIGUOUS | DMA_ATTR_NO_WARN;
+/// let c: CoherentAllocation<u64> =
+///     CoherentAllocation::alloc_attrs(dev, 4, GFP_KERNEL, attribs)?;
+/// # Ok::<(), Error>(()) }
+/// ```
+#[derive(Clone, Copy, PartialEq)]
+#[repr(transparent)]
+pub struct Attrs(u32);
+
Quoted 8 lines

rust/kernel/dma.rs line 42

Quoted 5 lines
rust/kernel/dma.rs new file +5 -0
+impl Attrs {
+    /// Get the raw representation of this attribute.
+    pub(crate) fn as_raw(self) -> crate::ffi::c_ulong {
+        self.0 as _
+    }

OT: I wonder why we do not have usize: From<u32>? It seems like this should be fine, even on 32 bit systems?

usize only implements From<unn> when it would work on all concievable platforms, so it's missing for u32 due to 16-bit platforms.

Alice

#5 lore raw

Re: [PATCH v15 02/11] rust: add dma coherent allocator abstraction.

In reply to Andreas Hindborg
Quoted 9 lines · Andreas Hindborg

The wording of in the other doc comments is different than this one and the two next ones. Consider aligning them:

Hints the DMA-mapping subsystem that ...

Tells the DMA-mapping subsystem ...

Indicates that the buffer ...

These come from the C side and are copy-pasted, so I suspect that was the reason -- they may want to have them in sync, so I didn't touch them.

Quoted 11 lines

I think it would be nice to have a description of what a coherent DMA region is here. From Documentation/core-api/dma-api.rst:

Consistent memory is memory for which a write by either the device or the processor can immediately be read by the processor or device without having to worry about caching effects. (You may however need to make sure to flush the processor's write buffers before telling devices to read that memory.)

I think consistent and coherent are used interchangeably in the kernel. If so, can we settle on just one of the terms in the rust code?

Abdiel has the diff ready for this, so he may send the patch (or you), but for the moment I decided to minimize changes -- up to the maintainers/reviewers now :)

Quoted 1 line
Quoted 1 line

+// DMA allocations potentially carry device resources (e.g.IOMMU mappings), hence for soundness

Nit: I think this should have a space after e.g. or a comma -- I didn't touch it, and it is a TODO anyway, but before I forget I mention it here.

Thanks!

Cheers,
Miguel

#6 lore raw

Re: [PATCH v15 02/11] rust: add dma coherent allocator abstraction.

Quoted 7 lines · Miguel Ojeda
Quoted 6 lines · Andreas Hindborg

The wording of in the other doc comments is different than this one and the two next ones. Consider aligning them:

Hints the DMA-mapping subsystem that ...

Quoted 7 lines
Quoted 3 lines

Tells the DMA-mapping subsystem ...

Indicates that the buffer ...

These come from the C side and are copy-pasted, so I suspect that was the reason -- they may want to have them in sync, so I didn't touch them.

Since this particular doc discussion is about wording and not semantics, I won't object too much. However, writing the docs for Rust is a very good chance to get _better_ docs and in general I would encourage taking advantage of that.

Best regards,
Andreas Hindborg

#7 lore raw

Re: [PATCH v15 02/11] rust: add dma coherent allocator abstraction.

In reply to Andreas Hindborg

Hi Andreas,

Quoted 4 lines

I think consistent and coherent are used interchangeably in the kernel. If so, can we settle on just one of the terms in the rust code?

I’d say let’s keep the coherent nomenclature. It immediately shows that dma_alloc_coherent() is being used.

— Daniel

author reviewer
#8 lore raw

PATCH v15 3/11 samples: rust: add Rust dma test sample driver

In reply to Abdiel Janulgue

Add 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 | 97 ++++++++++++++++++++++++++++++++++++++++
 3 files changed, 109 insertions(+)
 create mode 100644 samples/rust/rust_dma.rs
samples/rust/Kconfig +11 -0
index 3b6eae84b297..e2d14aa6beec 100644
@@ -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
index 0dbc6d90f1ef..1a9aff6e8d6a 100644
@@ -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 +97 -0

97 lines not on this page · raw message

Signature · 1 line
2.43.0
maintainer
#9 lore raw

Re: [PATCH v15 03/11] samples: rust: add Rust dma test sample driver

Hi Miguel,

Quoted 11 lines · Abdiel Janulgue

Add 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 | 97 ++++++++++++++++++++++++++++++++++++++++
 3 files changed, 109 insertions(+)
 create mode 100644 samples/rust/rust_dma.rs

This patch has a conflict with the driver-core tree, which you should also hit in linux-next.

The below diff should fix it.

- Danilo

samples/rust/rust_dma.rs +4 -4
index 1740140faba6..44e0e6aa5658 100644
@@ -4,10 +4,10 @@
 //!
 //! To make this driver probe, QEMU must be run with `-device pci-testdev`.
 
-use kernel::{bindings, dma::CoherentAllocation, pci, prelude::*};
+use kernel::{bindings, device::Core, dma::CoherentAllocation, pci, prelude::*, types::ARef};
 
 struct DmaSampleDriver {
-    pdev: pci::Device,
+    pdev: ARef<pci::Device>,
     ca: CoherentAllocation<MyStruct>,
 }
 
@@ -48,7 +48,7 @@ impl pci::Driver for DmaSampleDriver {
     type IdInfo = ();
     const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE;
 
-    fn probe(pdev: &mut pci::Device, _info: &Self::IdInfo) -> Result<Pin<KBox<Self>>> {
+    fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self>>> {
         dev_info!(pdev.as_ref(), "Probe DMA test driver.\n");
 
         let ca: CoherentAllocation<MyStruct> =
@@ -64,7 +64,7 @@ fn probe(pdev: &mut pci::Device, _info: &Self::IdInfo) -> Result<Pin<KBox<Self>>
 
         let drvdata = KBox::new(
             Self {
-                pdev: pdev.clone(),
+                pdev: pdev.into(),
                 ca,
             },
             GFP_KERNEL,
author reviewer NAK
#10 lore raw

PATCH v15 4/11 MAINTAINERS: add entry for Rust dma mapping helpers device driver API

In reply to Abdiel Janulgue

Add an entry for the Rust dma mapping helpers abstractions.

---
 MAINTAINERS | 13 +++++++++++++
 1 file changed, 13 insertions(+)
MAINTAINERS +13 -0
index 72b88f1638a2..4c0786336826 100644
@@ -6902,6 +6902,19 @@ 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 alloc-next
+F:	rust/kernel/dma.rs
+F:	samples/rust/rust_dma.rs
+
 DMA-BUF HEAPS FRAMEWORK
 M:	Sumit Semwal <[email protected]>
 R:	Benjamin Gaignard <[email protected]>
Signature · 1 line
2.43.0
author reviewer
#11 lore raw

PATCH v15 5/11 rust: dma: implement `dma::Device` trait

In reply to Abdiel Janulgue

From: Danilo Krummrich <[email protected]>

Add a trait that defines the DMA specific methods of devices.

The dma::Device trait should be implemented by (bus) device representations, where the underlying bus potentially supports DMA, such as pci::Device or platform::Device.

---
 rust/kernel/dma.rs | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)
rust/kernel/dma.rs +11 -4
index 9d00f9c49f47..834d00c1347e 100644
@@ -6,13 +6,20 @@
 
 use crate::{
     bindings, build_assert,
-    device::Device,
+    device,
     error::code::*,
     error::Result,
     transmute::{AsBytes, FromBytes},
     types::ARef,
 };
 
+/// Trait to be implemented by bus specific devices.
+///
+/// The [`Device`] trait should be implemented by bus specific device representations, where the
+/// underlying bus has potential support for DMA, such as [`crate::pci::Device`] or
+/// [crate::platform::Device].
+pub trait Device: AsRef<device::Device> {}
+
 /// Possible attributes associated with a DMA mapping.
 ///
 /// They can be combined with the operators `|`, `&`, and `!`.
@@ -130,7 +137,7 @@ pub mod attrs {
 // Hence, find a way to revoke the device resources of a `CoherentAllocation`, but not the
 // entire `CoherentAllocation` including the allocated memory itself.
 pub struct CoherentAllocation<T: AsBytes + FromBytes> {
-    dev: ARef<Device>,
+    dev: ARef<device::Device>,
     dma_handle: bindings::dma_addr_t,
     count: usize,
     cpu_addr: *mut T,
@@ -152,7 +159,7 @@ impl<T: AsBytes + FromBytes> CoherentAllocation<T> {
     /// # Ok::<(), Error>(()) }
     /// ```
     pub fn alloc_attrs(
-        dev: &Device,
+        dev: &device::Device,
         count: usize,
         gfp_flags: kernel::alloc::Flags,
         dma_attrs: Attrs,
@@ -194,7 +201,7 @@ pub fn alloc_attrs(
     /// Performs the same functionality as [`CoherentAllocation::alloc_attrs`], except the
     /// `dma_attrs` is 0 by default.
     pub fn alloc_coherent(
-        dev: &Device,
+        dev: &device::Device,
         count: usize,
         gfp_flags: kernel::alloc::Flags,
     ) -> Result<CoherentAllocation<T>> {
Signature · 1 line
2.43.0
author reviewer
#12 lore raw

PATCH v15 6/11 rust: dma: add dma addressing capabilities

In reply to Abdiel Janulgue

From: Danilo Krummrich <[email protected]>

Implement dma_set_mask() and dma_set_mask_and_coherent() in the dma::Device trait.

Those methods are used to inform the kernel about the device's DMA addressing capabilities.

---
 rust/helpers/dma.c     |  8 ++++++++
 rust/helpers/helpers.c |  1 +
 rust/kernel/dma.rs     | 46 +++++++++++++++++++++++++++++++++++++++---
 3 files changed, 52 insertions(+), 3 deletions(-)
 create mode 100644 rust/helpers/dma.c
rust/helpers/dma.c new file +8 -0
new file mode 100644
index 000000000000..8eb482386f93
@@ -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
index 0640b7e115be..8f3808c8b7fe 100644
@@ -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/dma.rs +43 -3

63 lines not on this page · raw message

Signature · 1 line
2.43.0
author reviewer
#13 lore raw

PATCH v15 7/11 rust: pci: implement the `dma::Device` trait

In reply to Abdiel Janulgue

From: Danilo Krummrich <[email protected]>

The PCI bus is potentially capable of performing DMA, hence implement the dma:Device trait for pci::Device.

---
 rust/kernel/pci.rs | 2 ++
 1 file changed, 2 insertions(+)
rust/kernel/pci.rs +2 -0
index f7b2743828ae..5839aa5d4098 100644
@@ -432,3 +432,5 @@ fn as_ref(&self) -> &device::Device {
         &self.0
     }
 }
+
+impl crate::dma::Device for Device {}
Signature · 1 line
2.43.0
author reviewer
#14 lore raw

PATCH v15 8/11 rust: platform: implement the `dma::Device` trait

In reply to Abdiel Janulgue

From: Danilo Krummrich <[email protected]>

The platform bus is potentially capable of performing DMA, hence implement the dma:Device trait for platform::Device.

---
 rust/kernel/platform.rs | 2 ++
 1 file changed, 2 insertions(+)
rust/kernel/platform.rs +2 -0
index 1297f5292ba9..a7bf3525313e 100644
@@ -198,3 +198,5 @@ fn as_ref(&self) -> &device::Device {
         &self.0
     }
 }
+
+impl crate::dma::Device for Device {}
Signature · 1 line
2.43.0
author reviewer
#15 lore raw

PATCH v15 9/11 rust: dma: use `dma::Device` in `CoherentAllocation`

In reply to Abdiel Janulgue

From: Danilo Krummrich <[email protected]>

Require a &dyn dma::Device in CoherentAllocation, such that DMA memory can only be allocated with devices on potentially DMA capable busses.

---
 rust/kernel/dma.rs       | 16 ++++++++--------
 samples/rust/rust_dma.rs |  2 +-
 2 files changed, 9 insertions(+), 9 deletions(-)
rust/kernel/dma.rs +8 -8
index fc66f1764c31..6d7aff6b360a 100644
@@ -57,10 +57,9 @@ fn dma_set_mask(&mut self, mask: u64) -> Result {
 /// # Examples
 ///
 /// ```
-/// use kernel::device::Device;
-/// use kernel::dma::{attrs::*, CoherentAllocation};
+/// use kernel::dma::{attrs::*, Device, CoherentAllocation};
 ///
-/// # fn test(dev: &Device) -> Result {
+/// # fn test(dev: &dyn Device) -> Result {
 /// let attribs = DMA_ATTR_FORCE_CONTIGUOUS | DMA_ATTR_NO_WARN;
 /// let c: CoherentAllocation<u64> =
 ///     CoherentAllocation::alloc_attrs(dev, 4, GFP_KERNEL, attribs)?;
@@ -178,16 +177,15 @@ impl<T: AsBytes + FromBytes> CoherentAllocation<T> {
     /// # Examples
     ///
     /// ```
-    /// use kernel::device::Device;
-    /// use kernel::dma::{attrs::*, CoherentAllocation};
+    /// use kernel::dma::{attrs::*, Device, CoherentAllocation};
     ///
-    /// # fn test(dev: &Device) -> Result {
+    /// # fn test(dev: &dyn Device) -> Result {
     /// let c: CoherentAllocation<u64> =
     ///     CoherentAllocation::alloc_attrs(dev, 4, GFP_KERNEL, DMA_ATTR_NO_WARN)?;
     /// # Ok::<(), Error>(()) }
     /// ```
     pub fn alloc_attrs(
-        dev: &device::Device,
+        dev: &dyn Device,
         count: usize,
         gfp_flags: kernel::alloc::Flags,
         dma_attrs: Attrs,
@@ -197,6 +195,8 @@ pub fn alloc_attrs(
             "It doesn't make sense for the allocated type to be a ZST"
         );
 
+        let dev = dev.as_ref();
+
         let size = count
             .checked_mul(core::mem::size_of::<T>())
             .ok_or(EOVERFLOW)?;
@@ -229,7 +229,7 @@ pub fn alloc_attrs(
     /// Performs the same functionality as [`CoherentAllocation::alloc_attrs`], except the
     /// `dma_attrs` is 0 by default.
     pub fn alloc_coherent(
-        dev: &device::Device,
+        dev: &dyn Device,
         count: usize,
         gfp_flags: kernel::alloc::Flags,
     ) -> Result<CoherentAllocation<T>> {
samples/rust/rust_dma.rs +1 -1
index 1740140faba6..4c7ebf66647a 100644
@@ -52,7 +52,7 @@ fn probe(pdev: &mut pci::Device, _info: &Self::IdInfo) -> Result<Pin<KBox<Self>>
         dev_info!(pdev.as_ref(), "Probe DMA test driver.\n");
 
         let ca: CoherentAllocation<MyStruct> =
-            CoherentAllocation::alloc_coherent(pdev.as_ref(), TEST_VALUES.len(), GFP_KERNEL)?;
+            CoherentAllocation::alloc_coherent(pdev, TEST_VALUES.len(), GFP_KERNEL)?;
 
         || -> Result {
             for (i, value) in TEST_VALUES.into_iter().enumerate() {
Signature · 1 line
2.43.0
#16 lore raw

Re: [PATCH v15 09/11] rust: dma: use `dma::Device` in `CoherentAllocation`

Hi Abdiel,

Quoted 8 lines · Abdiel Janulgue

From: Danilo Krummrich <[email protected]>

Require a &dyn dma::Device in CoherentAllocation, such that DMA memory can only be allocated with devices on potentially DMA capable busses.

Did you see my comment on v14 [1]?

Best regards,
Andreas Hindborg

[1] https://lore.kernel.org/lkml/[email protected]/

author reviewer
#17 lore raw

PATCH v15 10/11 rust: samples: dma: set DMA mask

In reply to Abdiel Janulgue

From: Danilo Krummrich <[email protected]>

Set a DMA mask for the pci::Device in the Rust DMA sample driver.

---
 samples/rust/rust_dma.rs | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
samples/rust/rust_dma.rs +8 -1
index 4c7ebf66647a..39b6050aa3b6 100644
@@ -4,7 +4,12 @@
 //!
 //! To make this driver probe, QEMU must be run with `-device pci-testdev`.
 
-use kernel::{bindings, dma::CoherentAllocation, pci, prelude::*};
+use kernel::{
+    bindings,
+    dma::{CoherentAllocation, Device},
+    pci,
+    prelude::*,
+};
 
 struct DmaSampleDriver {
     pdev: pci::Device,
@@ -51,6 +56,8 @@ impl pci::Driver for DmaSampleDriver {
     fn probe(pdev: &mut pci::Device, _info: &Self::IdInfo) -> Result<Pin<KBox<Self>>> {
         dev_info!(pdev.as_ref(), "Probe DMA test driver.\n");
 
+        pdev.dma_set_mask_and_coherent(kernel::dma::dma_bit_mask(64))?;
+
         let ca: CoherentAllocation<MyStruct> =
             CoherentAllocation::alloc_coherent(pdev, TEST_VALUES.len(), GFP_KERNEL)?;
 
Signature · 1 line
2.43.0
author reviewer
#18 lore raw

PATCH v15 11/11 rust: dma: add as_slice/write functions for CoherentAllocation

In reply to Abdiel Janulgue

Add unsafe accessors for the region for reading or writing large blocks of data.

---
 rust/kernel/dma.rs | 87 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 87 insertions(+)
rust/kernel/dma.rs +87 -0
index 6d7aff6b360a..027ef75a461a 100644
@@ -253,6 +253,93 @@ 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 [`CoherentAllocation::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
#21 lore raw
In reply to Abdiel Janulgue

Hi Abdiel,

Quoted 9 lines · Abdiel Janulgue

This series adds the rust bindings for the dma coherent allocator which is needed for nova-core[0].

For v15, document safety comments on the exception of usage on read_volatile and write_volatile as suggested by Boqun Feng.

This is tested on a Nvidia GA104 GPU device using PoC code which parses and loads the GSP firmware via DMA.

I messed up and replied to v14 of the series for patch 3, 6 (x2) and 9. Comments still apply to v15.

Best regards,
Andreas Hindborg

#22 lore raw
In reply to Abdiel Janulgue
Quoted 9 lines · Abdiel Janulgue

This series adds the rust bindings for the dma coherent allocator which is needed for nova-core[0].

For v15, document safety comments on the exception of usage on read_volatile and write_volatile as suggested by Boqun Feng.

This is tested on a Nvidia GA104 GPU device using PoC code which parses and loads the GSP firmware via DMA.

Applied (up to the MAINTAINERS patch, as discussed) to rust-next -- thanks everyone!

[ Removed period. - Miguel ]

[ Renamed Kconfig symbol and moved it up. Migrated to the new
authors key in module!. Fixed module name in description and typo in commit message. - Miguel ]

Cheers,
Miguel