[RFC PATCH v2 02/10] rust: dma: add Setup, Params and Handle
From: Matteo Kloiber
Date: Sun Nov 29 2026 - 17:25:33 EST
Rust drivers can allocate or map DMA memory without first setting the
DMA parameters. A missing setter leaves the existing value in use,
which is the bus default or whatever a previously bound driver left
behind. This happened with Nova's maximum segment size, fixed in
commit 6bd5eaeb9827 ("gpu: nova-core: declare unlimited DMA max
segment size").
Add a dma::Setup token to the PCI and platform InitTokens passed to
probe(). Drivers can read device registers before they configure DMA.
Drivers that do not use DMA can discard the token.
Add dma::Params for the streaming mask, coherent mask and maximum
segment size. Some(value) sets a parameter; None keeps its current
value. Do not implement Default, so drivers must specify every field,
including new fields.
Setup::configure() consumes the token and returns a copyable
dma::Handle on success. The handle cannot change the DMA parameters.
Nothing requires the handle yet. The DMA APIs still take a device and
the dma::Device setters still exist, so the ordering is not enforced
before the end of this series: the following patches convert the
drivers, make the DMA APIs take a handle and remove the setters.
Suggested-by: Alexandre Courbot <acourbot@xxxxxxxxxx>
Link: https://lore.kernel.org/DLHH0K25NLX5.616R4D860TXU@xxxxxxxxxx
Link: https://lore.kernel.org/DLR1JCUWS824.35QJU45D2W9ZE@xxxxxxxxxx
Signed-off-by: Matteo Kloiber <kernel@xxxxxxxxxxx>
---
rust/kernel/dma.rs | 112 ++++++++++++++++++++++++++++++++++++++++
rust/kernel/pci.rs | 12 ++++-
rust/kernel/platform.rs | 12 ++++-
3 files changed, 132 insertions(+), 4 deletions(-)
diff --git a/rust/kernel/dma.rs b/rust/kernel/dma.rs
index 580e1c3427bc..9c3cbce77ce9 100644
--- a/rust/kernel/dma.rs
+++ b/rust/kernel/dma.rs
@@ -31,6 +31,7 @@
uaccess::UserSliceWriter, //
};
use core::{
+ num::NonZeroU32,
ops::{
Deref,
DerefMut, //
@@ -48,6 +49,117 @@
/// Note that this may be `u64` even on 32-bit architectures.
pub type DmaAddress = bindings::dma_addr_t;
+/// DMA parameters passed to [`Setup::configure`].
+///
+/// `Some(value)` sets a parameter and `None` keeps its current value. The current value is whatever
+/// the bus set up or a previously bound driver left behind, so it is not necessarily the bus
+/// default. There is intentionally no `Default` implementation, so drivers have to decide on every
+/// parameter, including ones added later.
+///
+/// # Examples
+///
+/// ```
+/// # use core::num::NonZeroU32;
+/// use kernel::dma::{self, Coherent, DmaMask};
+///
+/// # fn test(setup: dma::Setup<'_>) -> Result {
+/// let dma = setup.configure(dma::Params {
+/// streaming_mask: Some(DmaMask::new::<64>()),
+/// coherent_mask: Some(DmaMask::new::<64>()),
+/// max_seg_size: Some(NonZeroU32::MAX),
+/// })?;
+///
+/// let _buf = Coherent::<u64>::zeroed(dma.device(), GFP_KERNEL)?;
+/// # Ok::<(), Error>(()) }
+/// ```
+pub struct Params {
+ /// Address mask for streaming DMA mappings.
+ pub streaming_mask: Option<DmaMask>,
+ /// Address mask for coherent DMA allocations.
+ pub coherent_mask: Option<DmaMask>,
+ /// Maximum length in bytes of a DMA segment supported by the device.
+ ///
+ /// Use `Some(NonZeroU32::MAX)` if the device has no segment size limit.
+ pub max_seg_size: Option<NonZeroU32>,
+}
+
+/// Token for configuring a device's DMA parameters.
+///
+/// The bus passes it to the driver's `probe()` callback. The driver can access the device, e.g. to
+/// read its capabilities, before calling [`Setup::configure`], which consumes the token. Drivers
+/// that don't use DMA can drop it.
+///
+/// # Invariants
+///
+/// - The bus has initialized the device's DMA parameters.
+/// - There is only one `Setup` per driver binding, and no [`Handle`] has been created for it yet.
+/// - No DMA allocation or mapping for this device can run concurrently with
+/// [`Setup::configure`], and nothing else changes the DMA parameters while the device is bound.
+pub struct Setup<'bound> {
+ dev: &'bound device::Device<Bound>,
+}
+
+impl<'bound> Setup<'bound> {
+ /// Creates the setup token passed to a driver's probe callback.
+ ///
+ /// # Safety
+ ///
+ /// The caller must ensure the invariants of [`Self`], including uniqueness of the token.
+ #[inline]
+ pub(crate) unsafe fn new(dev: &'bound device::Device<Bound>) -> Self {
+ // INVARIANT: The safety requirements of this function guarantee the invariants of `Setup`.
+ Self { dev }
+ }
+
+ /// Applies `params` and returns a [`Handle`] for DMA allocations and mappings.
+ ///
+ /// If a setter fails, its error is returned and parameters applied before it are not restored.
+ pub fn configure(self, params: Params) -> Result<Handle<'bound>> {
+ let dev = self.dev.as_raw();
+
+ if let Some(mask) = params.streaming_mask {
+ // SAFETY: `dev` is valid. The `Setup` invariants exclude concurrent DMA operations
+ // and other parameter setters, and consuming the token prevents reconfiguration.
+ to_result(unsafe { bindings::dma_set_mask(dev, mask.value()) })?;
+ }
+ if let Some(mask) = params.coherent_mask {
+ // SAFETY: `dev` is valid. The `Setup` invariants exclude concurrent DMA operations
+ // and other parameter setters, and consuming the token prevents reconfiguration.
+ to_result(unsafe { bindings::dma_set_coherent_mask(dev, mask.value()) })?;
+ }
+ if let Some(size) = params.max_seg_size {
+ // SAFETY: `dev` is valid and its DMA parameters are initialized. The `Setup`
+ // invariants exclude concurrent DMA operations and other parameter setters,
+ // and consuming the token prevents reconfiguration.
+ unsafe { bindings::dma_set_max_seg_size(dev, size.get()) };
+ }
+
+ // INVARIANT: All requested setters succeeded. The `Setup` invariants prevent further
+ // changes while the device is bound to the driver.
+ Ok(Handle { dev: self.dev })
+ }
+}
+
+/// Handle for DMA allocations and mappings on a configured device.
+///
+/// Returned by [`Setup::configure`]. It can be copied freely, but cannot change the DMA parameters.
+///
+/// # Invariants
+///
+/// The requested DMA parameters have been applied and do not change during `'bound`.
+#[derive(Clone, Copy)]
+pub struct Handle<'bound> {
+ dev: &'bound device::Device<Bound>,
+}
+
+impl<'bound> Handle<'bound> {
+ /// Returns the device associated with this DMA handle.
+ #[inline]
+ pub fn device(self) -> &'bound device::Device<Bound> {
+ self.dev
+ }
+}
+
/// Trait to be implemented by DMA capable bus devices.
///
/// The [`dma::Device`](Device) trait should be implemented by bus specific device representations,
diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs
index 1d61fcb64b03..10b00b641dea 100644
--- a/rust/kernel/pci.rs
+++ b/rust/kernel/pci.rs
@@ -12,6 +12,7 @@
RawDeviceId,
RawDeviceIdIndex, //
},
+ dma,
driver,
error::{
from_result,
@@ -147,7 +148,11 @@ extern "C" fn probe_callback(
let info = unsafe { id.info_unchecked_opt::<T::IdInfo>() };
from_result(|| {
- let data = T::probe(pdev, InitTokens { _p: PhantomData }, info);
+ // SAFETY: The bus initializes the DMA parameters before probing. This is the only
+ // setup token issued for this binding, and no driver code has run for the binding
+ // yet.
+ let dma = unsafe { dma::Setup::new(pdev.as_ref()) };
+ let data = T::probe(pdev, InitTokens { dma }, info);
pdev.as_ref().set_drvdata(data)?;
Ok(0)
@@ -454,7 +459,8 @@ macro_rules! pci_device_table {
/// Initialization tokens passed to a PCI driver's [`Driver::probe`] callback.
#[non_exhaustive]
pub struct InitTokens<'bound> {
- _p: PhantomData<&'bound ()>,
+ /// Token for configuring DMA, see [`dma::Setup`].
+ pub dma: dma::Setup<'bound>,
}
/// The PCI driver trait.
@@ -518,6 +524,8 @@ pub trait Driver {
///
/// Called when a new pci device is added or discovered. Implementers should
/// attempt to initialize the device here.
+ ///
+ /// Drivers that use DMA must configure it through `tokens.dma` first.
fn probe<'bound>(
dev: &'bound Device<device::Core<'_>>,
tokens: InitTokens<'bound>,
diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs
index a7b33e229a30..bdb2c5c09b21 100644
--- a/rust/kernel/platform.rs
+++ b/rust/kernel/platform.rs
@@ -12,6 +12,7 @@
self,
Bound, //
},
+ dma,
driver,
error::{
from_result,
@@ -104,7 +105,11 @@ extern "C" fn probe_callback(pdev: *mut bindings::platform_device) -> kernel::ff
let info = unsafe { <Self as driver::Adapter>::id_info(pdev.as_ref()) };
from_result(|| {
- let data = T::probe(pdev, InitTokens { _p: PhantomData }, info);
+ // SAFETY: The bus initializes the DMA parameters before probing. This is the only
+ // setup token issued for this binding, and no driver code has run for the binding
+ // yet.
+ let dma = unsafe { dma::Setup::new(pdev.as_ref()) };
+ let data = T::probe(pdev, InitTokens { dma }, info);
pdev.as_ref().set_drvdata(data)?;
Ok(0)
@@ -162,7 +167,8 @@ macro_rules! module_platform_driver {
/// Initialization tokens passed to a platform driver's [`Driver::probe`] callback.
#[non_exhaustive]
pub struct InitTokens<'bound> {
- _p: PhantomData<&'bound ()>,
+ /// Token for configuring DMA, see [`dma::Setup`].
+ pub dma: dma::Setup<'bound>,
}
/// The platform driver trait.
@@ -234,6 +240,8 @@ pub trait Driver {
///
/// Called when a new platform device is added or discovered.
/// Implementers should attempt to initialize the device here.
+ ///
+ /// Drivers that use DMA must configure it through `tokens.dma` first.
fn probe<'bound>(
dev: &'bound Device<device::Core<'_>>,
tokens: InitTokens<'bound>,
--
2.51.2