[PATCH 5/8] rust: dma: add methods to unsafely create reference from subview

Gary Guo
2026-03-23T15:38:49Z

From: Gary Guo <gary@garyguo.net>

Implement `Io` for `Coherent`, so now `dma::Coherent` can be used with I/O
projections.

This allows the `as_ref()` and `as_mut()` API to be used in smaller region
than the whole DMA allocation itself. For example, if a ring buffer is shared
between GPU and CPU, users may now use the `io_project!` API to obtain a view
of the buffer that is unified owned by the CPU and get a reference.

Signed-off-by: Gary Guo <gary@garyguo.net>
---
rust/kernel/dma.rs | 56 ++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 56 insertions(+)

diff --git a/rust/kernel/dma.rs b/rust/kernel/dma.rs
index 779d4babab9a..ae2939abc166 100644
--- a/rust/kernel/dma.rs
+++ b/rust/kernel/dma.rs
@@ -12,6 +12,10 @@
Core, //
},
error::to_result,
+ io::{
+ Io,
+ IoCapable, //
+ },
prelude::*,
ptr::KnownSize,
sync::aref::ARef,
@@ -864,6 +868,58 @@ fn drop(&mut self) {
// can be sent to another thread.
unsafe impl<T: KnownSize + Send + ?Sized> Send for Coherent<T> {}

+impl<T: ?Sized + KnownSize> Io for Coherent<T> {
+ type Type = T;
+
+ #[inline]
+ fn as_ptr(&self) -> *mut Self::Type {
+ self.as_mut_ptr()
+ }
+}
+
+impl<'a, B: ?Sized + KnownSize, T: ?Sized> crate::io::View<'a, Coherent, T> {
+ /// Returns a DMA handle which may be given to the device as the DMA address base of
+ /// the region.
+ #[inline]
+ pub fn dma_handle(&self) -> DmaAddress {
+ let base = self.io();
+ let offset = self.as_ptr().addr() - base.as_ptr().addr();
+ base.dma_handle() + offset as DmaAddress
+ }
+
+ /// Returns a reference to the data in the region.
+ ///
+ /// # Safety
+ ///
+ /// * Callers must ensure that the device does not read/write to/from memory while the returned
+ /// slice is live.
+ /// * Callers must ensure that this call does not race with a write to the same region while
+ /// the returned slice is live.
+ #[inline]
+ pub unsafe fn as_ref(self) -> &'a T {
+ let ptr = self.as_ptr();
+ // SAFETY: pointer is aligned and valid per type invariant of `View`. Aliasing rule is
+ // satisfied per safety requirement.
+ unsafe { &*ptr }
+ }
+
+ /// Returns a mutable reference to the data in the region.
+ ///
+ /// # Safety
+ ///
+ /// * Callers must ensure that the device does not read/write to/from memory 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.
+ #[inline]
+ pub unsafe fn as_mut(self) -> &'a mut T {
+ let ptr = self.as_ptr();
+ // SAFETY: pointer is aligned and valid per type invariant of `View`. Aliasing rule is
+ // satisfied per safety requirement.
+ unsafe { &mut *ptr }
+ }
+}
+
/// Reads a field of an item from an allocated region of structs.
///
/// The syntax is of the form `kernel::dma_read!(dma, proj)` where `dma` is an expression evaluating
--
2.51.2