From: Matteo Kloiber <kernel@matt3o12.de>
To: Danilo Krummrich <dakr@kernel.org>,
Alexandre Courbot <acourbot@nvidia.com>,
Alice Ryhl <aliceryhl@google.com>,
Abdiel Janulgue <abdiel.janulgue@gmail.com>,
Robin Murphy <robin.murphy@arm.com>,
Andreas Hindborg <a.hindborg@kernel.org>,
Gary Guo <gary@garyguo.net>
Cc: "Daniel Almeida" <daniel.almeida@collabora.com>,
"Miguel Ojeda" <ojeda@kernel.org>,
"David Airlie" <airlied@gmail.com>,
"Simona Vetter" <simona@ffwll.ch>,
"Bjorn Helgaas" <bhelgaas@google.com>,
"Krzysztof Wilczyński" <kwilczynski@kernel.org>,
"Greg Kroah-Hartman" <gregkh@linuxfoundation.org>,
rust-for-linux@vger.kernel.org, driver-core@lists.linux.dev,
dri-devel@lists.freedesktop.org, nova-gpu@lists.linux.dev,
linux-kernel@vger.kernel.org,
"Matteo Kloiber" <kernel@matt3o12.de>
Subject: [RFC PATCH v2 02/10] rust: dma: add Setup, Params and Handle
Date: Sun, 29 Nov 2026 23:24:21 +0100 [thread overview]
Message-ID: <20261129222429.2380652-3-kernel@matt3o12.de> (raw)
In-Reply-To: <20261129222429.2380652-1-kernel@matt3o12.de>
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@nvidia.com>
Link: https://lore.kernel.org/DLHH0K25NLX5.616R4D860TXU@nvidia.com
Link: https://lore.kernel.org/DLR1JCUWS824.35QJU45D2W9ZE@nvidia.com
Signed-off-by: Matteo Kloiber <kernel@matt3o12.de>
---
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
next prev parent reply other threads:[~2026-11-29 22:25 UTC|newest]
Thread overview: 11+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-11-29 22:24 [RFC PATCH v2 00/10] rust: dma: require device configuration before DMA Matteo Kloiber
2026-11-29 22:24 ` [RFC PATCH v2 01/10] rust: pci, platform: pass InitTokens to probe() Matteo Kloiber
2026-11-29 22:24 ` Matteo Kloiber [this message]
2026-11-29 22:24 ` [RFC PATCH v2 03/10] gpu: nova-core: configure DMA through dma::Setup Matteo Kloiber
2026-11-29 22:24 ` [RFC PATCH v2 04/10] drm/tyr: " Matteo Kloiber
2026-11-29 22:24 ` [RFC PATCH v2 05/10] samples: rust: dma: " Matteo Kloiber
2026-11-29 22:24 ` [RFC PATCH v2 06/10] rust: dma: require a Handle for coherent allocations Matteo Kloiber
2026-11-29 22:24 ` [RFC PATCH v2 07/10] rust: scatterlist: require a dma::Handle for SGTable::new() Matteo Kloiber
2026-11-29 22:24 ` [RFC PATCH v2 08/10] rust: iommu: require a dma::Handle for IoPageTable::new() Matteo Kloiber
2026-11-29 22:24 ` [RFC PATCH v2 09/10] rust: drm: require a dma::Handle for shmem sg_table() Matteo Kloiber
2026-11-29 22:24 ` [RFC PATCH v2 10/10] rust: dma: remove the Device trait and its setters Matteo Kloiber
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20261129222429.2380652-3-kernel@matt3o12.de \
--to=kernel@matt3o12.de \
--cc=a.hindborg@kernel.org \
--cc=abdiel.janulgue@gmail.com \
--cc=acourbot@nvidia.com \
--cc=airlied@gmail.com \
--cc=aliceryhl@google.com \
--cc=bhelgaas@google.com \
--cc=dakr@kernel.org \
--cc=daniel.almeida@collabora.com \
--cc=dri-devel@lists.freedesktop.org \
--cc=driver-core@lists.linux.dev \
--cc=gary@garyguo.net \
--cc=gregkh@linuxfoundation.org \
--cc=kwilczynski@kernel.org \
--cc=linux-kernel@vger.kernel.org \
--cc=nova-gpu@lists.linux.dev \
--cc=ojeda@kernel.org \
--cc=robin.murphy@arm.com \
--cc=rust-for-linux@vger.kernel.org \
--cc=simona@ffwll.ch \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
all inboxes | Powered by JetHome®