mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [RFC PATCH v2 00/10] rust: dma: require device configuration before DMA
@ 2026-11-29 22:24 Matteo Kloiber
  2026-11-29 22:24 ` [RFC PATCH v2 01/10] rust: pci, platform: pass InitTokens to probe() Matteo Kloiber
                   ` (9 more replies)
  0 siblings, 10 replies; 11+ messages in thread
From: Matteo Kloiber @ 2026-11-29 22:24 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot, Alice Ryhl, Abdiel Janulgue,
	Robin Murphy, Andreas Hindborg, Gary Guo
  Cc: Daniel Almeida, Miguel Ojeda, David Airlie, Simona Vetter,
	Bjorn Helgaas, Krzysztof Wilczyński, Greg Kroah-Hartman,
	rust-for-linux, driver-core, dri-devel, nova-gpu, linux-kernel,
	Matteo Kloiber

This is the RFC that came out of the max_seg_size discussion [1]. It
implements the DMA setup token Alexandre proposed there, passed to
probe() through the InitTokens struct that he and Danilo suggested in
[2].

A driver now has to configure DMA before it can allocate or map
anything:

    let pci::InitTokens { dma: setup, .. } = tokens;

    let dma = setup.configure(dma::Params {
        streaming_mask: Some(mask),
        coherent_mask: Some(mask),
        max_seg_size: Some(NonZeroU32::MAX),
    })?;

    let buf = Coherent::<u64>::zeroed(dma, GFP_KERNEL)?;

configure() consumes the token and returns a copyable dma::Handle.
Coherent allocations, SGTable::new(), IoPageTable::new() and the shmem
sg_table() take that handle instead of a device, so they cannot be
called before configuration and the parameters cannot change
afterwards. The unsafe dma::Device setters are gone. Drivers that do no
DMA ignore the token.

- Patch 1 adds InitTokens to the PCI and platform probe() signature.
  It is mechanical and the only patch that touches drivers without DMA.
- Patch 2 adds dma::Setup, dma::Params and dma::Handle, and hands out
  the token through InitTokens. Nothing has to use them yet.
- Patches 3-5 convert nova-core, Tyr and the DMA sample to configure()
  and pass the handle to the code that allocates or maps. The DMA APIs
  still take a device at this point, so the drivers hand them
  dma.device().
- Patches 6-9 make the DMA APIs take the handle, one API per patch:
  coherent allocations, SGTable::new(), IoPageTable::new() and the
  shmem sg_table().
- Patch 10 removes the dma::Device trait and its setters. The ordering
  is only enforced from here on, because until then the old setters
  still exist next to the new token.

Changes in v2:

- Split the main patch into the steps above (Danilo).
- Drop "gpu: nova-core: build Gpu inside pin_init_scope". Gpu now
  stores the dma::Handle in a field, where the fields initialized
  after it can use it (Danilo). GspResources keeps a copy rather than
  a reference, since the handle is Copy. The DMA parameters are again
  set at the same point in Gpu::new() as before the series.
- Add the missing INVARIANT comments to Setup::new() and
  Handle::new_for_test(), and mark the small Setup and Handle methods
  #[inline] (Sashiko).
- Drop the DMA paragraph from the drm::Registration::new()
  documentation. It read like a requirement on an unsafe function, but
  it is not a safety requirement.
- Rename the dma::Handle parameters of the coherent allocation
  constructors from dev to dma.
- Rebase onto current drm-rust-next and pass InitTokens to the new
  SR-IOV sample drivers.

v1: https://lore.kernel.org/20261123203926.1787169-1-kernel@matt3o12.de

Design decisions (feedback welcome):

- Params has no Default, so adding a field later requires updating
  every in-tree DMA driver. Because the kernel is a mono repo, I think
  this is the right tradeoff. It forces a deliberate choice between
  None and an explicit value for each driver rather than silently
  preserving existing behaviour. InitTokens is #[non_exhaustive]
  because most drivers will not care about unrelated tokens.

- configure() consumes the token even on error, so a driver cannot retry
  with a different mask. dma-api-howto.rst states that drivers should
  fail probe if setting the mask fails, and consuming the token enforces
  that. If a driver ever needs to probe supported masks first, a
  separate query method fits better than returning the token on error.

- Only PCI and platform probe() hand out a token. An auxiliary driver
  that performs DMA on behalf of its parent should receive the parent's
  dma::Handle rather than configuring DMA itself. No in-tree auxiliary
  driver needs this yet.

- Tyr keeps its current segment size (max_seg_size: None, with a TODO).
  Panthor sets UINT_MAX for the same hardware, so Tyr probably should
  too, but I left that out to avoid behaviour changes in this series. I
  can either send this as a separate patch or include it in the non-RFC
  series.

- pci::Driver::DRIVER_MANAGED_DMA was merged in the meantime as an
  unsafe marker "until the DMA setup tokens exist". Such a driver still
  receives a dma::Setup, which it has promised not to use. Withholding
  the token would let the marker become safe. I left that out of this
  RFC and can add it once the token design is settled.

One limitation: DRM C callbacks that map memory on the driver's behalf
do not go through the handle. For those the ordering is not enforced.

Every patch builds with CLIPPY=1, and the Rust KUnit suites and
doctests pass on each of them (x86_64, QEMU). nova-core and Tyr are
compile-tested only.

An LLM assisted with the design and implementation, including writing
all comments and text. I have reviewed all of it.

Based on drm-rust-next.

[1] https://lore.kernel.org/DLHH0K25NLX5.616R4D860TXU@nvidia.com
[2] https://lore.kernel.org/DLR1JCUWS824.35QJU45D2W9ZE@nvidia.com

Matteo Kloiber (10):
  rust: pci, platform: pass InitTokens to probe()
  rust: dma: add Setup, Params and Handle
  gpu: nova-core: configure DMA through dma::Setup
  drm/tyr: configure DMA through dma::Setup
  samples: rust: dma: configure DMA through dma::Setup
  rust: dma: require a Handle for coherent allocations
  rust: scatterlist: require a dma::Handle for SGTable::new()
  rust: iommu: require a dma::Handle for IoPageTable::new()
  rust: drm: require a dma::Handle for shmem sg_table()
  rust: dma: remove the Device trait and its setters

 drivers/cpufreq/rcpufreq_dt.rs                |   1 +
 drivers/gpu/drm/tyr/driver.rs                 |  18 +-
 drivers/gpu/drm/tyr/fw.rs                     |  11 +-
 drivers/gpu/drm/tyr/mmu/address_space.rs      |   7 +-
 drivers/gpu/drm/tyr/vm.rs                     |  28 +-
 drivers/gpu/nova-core/driver.rs               |   4 +-
 drivers/gpu/nova-core/falcon.rs               |  13 +-
 drivers/gpu/nova-core/fb.rs                   |  11 +-
 .../nova-core/firmware/fwsec/bootloader.rs    |  13 +-
 drivers/gpu/nova-core/firmware/gsp.rs         |  18 +-
 drivers/gpu/nova-core/firmware/gsp_fmc.rs     |  10 +-
 drivers/gpu/nova-core/firmware/radix3.rs      |  17 +-
 drivers/gpu/nova-core/firmware/riscv.rs       |  11 +-
 drivers/gpu/nova-core/fsp.rs                  |  20 +-
 drivers/gpu/nova-core/gpu.rs                  |  47 ++-
 drivers/gpu/nova-core/gsp.rs                  |  19 +-
 drivers/gpu/nova-core/gsp/boot.rs             |   2 +-
 drivers/gpu/nova-core/gsp/cmdq.rs             |  14 +-
 drivers/gpu/nova-core/gsp/hal/gh100.rs        |   9 +-
 drivers/gpu/nova-core/gsp/hal/tu102.rs        |  24 +-
 drivers/gpu/nova-core/gsp/logbuffer.rs        |  23 +-
 drivers/pwm/pwm_th1520.rs                     |   1 +
 rust/helpers/dma.c                            |   6 -
 rust/kernel/cpufreq.rs                        |   1 +
 rust/kernel/dma.rs                            | 334 ++++++++++--------
 rust/kernel/drm/gem/shmem.rs                  |  23 +-
 rust/kernel/io/mem.rs                         |   2 +
 rust/kernel/iommu/pgtable.rs                  |  24 +-
 rust/kernel/pci.rs                            |  21 +-
 rust/kernel/platform.rs                       |  21 +-
 rust/kernel/scatterlist.rs                    |  22 +-
 samples/rust/rust_debugfs.rs                  |   1 +
 samples/rust/rust_dma.rs                      |  18 +-
 samples/rust/rust_driver_auxiliary.rs         |   1 +
 samples/rust/rust_driver_pci.rs               |   1 +
 samples/rust/rust_driver_platform.rs          |   1 +
 samples/rust/rust_driver_sriov/pf.rs          |   1 +
 samples/rust/rust_driver_sriov/vf.rs          |   1 +
 samples/rust/rust_i2c_client.rs               |   1 +
 samples/rust/rust_soc.rs                      |   1 +
 40 files changed, 458 insertions(+), 343 deletions(-)


base-commit: abfb640b2374e26de8ff81d488c39d8254db538e
-- 
2.51.2


^ permalink raw reply	[flat|nested] 11+ messages in thread

* [RFC PATCH v2 01/10] rust: pci, platform: pass InitTokens to probe()
  2026-11-29 22:24 [RFC PATCH v2 00/10] rust: dma: require device configuration before DMA Matteo Kloiber
@ 2026-11-29 22:24 ` Matteo Kloiber
  2026-11-29 22:24 ` [RFC PATCH v2 02/10] rust: dma: add Setup, Params and Handle Matteo Kloiber
                   ` (8 subsequent siblings)
  9 siblings, 0 replies; 11+ messages in thread
From: Matteo Kloiber @ 2026-11-29 22:24 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot, Alice Ryhl, Abdiel Janulgue,
	Robin Murphy, Andreas Hindborg, Gary Guo
  Cc: Daniel Almeida, Miguel Ojeda, David Airlie, Simona Vetter,
	Bjorn Helgaas, Krzysztof Wilczyński, Greg Kroah-Hartman,
	rust-for-linux, driver-core, dri-devel, nova-gpu, linux-kernel,
	Matteo Kloiber

Some capabilities should only be available to a driver while it binds
to a device, for example configuring the device for DMA before any
memory is allocated or mapped. A probe-time token lets the type system
enforce such ordering, but adding a new argument to probe() for every
token would touch every driver each time.

Add an InitTokens struct to the PCI and platform buses and pass it to
Driver::probe(). Buses add new tokens as fields of this struct. It is
marked #[non_exhaustive], so drivers destructure it with `..` and
adding tokens later does not break them.

The struct carries no tokens yet. Update all drivers, samples and
doctests to accept and ignore it.

Suggested-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/DLR1JCUWS824.35QJU45D2W9ZE@nvidia.com
Signed-off-by: Matteo Kloiber <kernel@matt3o12.de>
---
 drivers/cpufreq/rcpufreq_dt.rs        |  1 +
 drivers/gpu/drm/tyr/driver.rs         |  1 +
 drivers/gpu/nova-core/driver.rs       |  1 +
 drivers/pwm/pwm_th1520.rs             |  1 +
 rust/kernel/cpufreq.rs                |  1 +
 rust/kernel/io/mem.rs                 |  2 ++
 rust/kernel/pci.rs                    | 10 +++++++++-
 rust/kernel/platform.rs               | 10 +++++++++-
 samples/rust/rust_debugfs.rs          |  1 +
 samples/rust/rust_dma.rs              |  1 +
 samples/rust/rust_driver_auxiliary.rs |  1 +
 samples/rust/rust_driver_pci.rs       |  1 +
 samples/rust/rust_driver_platform.rs  |  1 +
 samples/rust/rust_driver_sriov/pf.rs  |  1 +
 samples/rust/rust_driver_sriov/vf.rs  |  1 +
 samples/rust/rust_i2c_client.rs       |  1 +
 samples/rust/rust_soc.rs              |  1 +
 17 files changed, 34 insertions(+), 2 deletions(-)

diff --git a/drivers/cpufreq/rcpufreq_dt.rs b/drivers/cpufreq/rcpufreq_dt.rs
index 2b1f18b7a1e7..a6e314f4d809 100644
--- a/drivers/cpufreq/rcpufreq_dt.rs
+++ b/drivers/cpufreq/rcpufreq_dt.rs
@@ -212,6 +212,7 @@ impl platform::Driver for CPUFreqDTDriver {
 
     fn probe<'bound>(
         pdev: &'bound platform::Device<Core<'_>>,
+        _tokens: platform::InitTokens<'bound>,
         _id_info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self, Error> + 'bound {
         cpufreq::Registration::<CPUFreqDTDriver>::new_foreign_owned(pdev.as_ref())?;
diff --git a/drivers/gpu/drm/tyr/driver.rs b/drivers/gpu/drm/tyr/driver.rs
index 557f2ec0a767..7650ade4ad72 100644
--- a/drivers/gpu/drm/tyr/driver.rs
+++ b/drivers/gpu/drm/tyr/driver.rs
@@ -119,6 +119,7 @@ impl platform::Driver for TyrPlatformDriver {
 
     fn probe<'bound>(
         pdev: &'bound platform::Device<Core<'_>>,
+        _tokens: platform::InitTokens<'bound>,
         _info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
         pin_init::pin_init_scope(move || {
diff --git a/drivers/gpu/nova-core/driver.rs b/drivers/gpu/nova-core/driver.rs
index bea1b1b0844c..365e77ff0cc4 100644
--- a/drivers/gpu/nova-core/driver.rs
+++ b/drivers/gpu/nova-core/driver.rs
@@ -101,6 +101,7 @@ impl pci::Driver for NovaCoreDriver {
 
     fn probe<'bound>(
         pdev: &'bound pci::Device<Core<'_>>,
+        _tokens: pci::InitTokens<'bound>,
         _info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
         dev_dbg!(pdev, "Probe Nova Core GPU driver.\n");
diff --git a/drivers/pwm/pwm_th1520.rs b/drivers/pwm/pwm_th1520.rs
index 728993998446..2486333c4a91 100644
--- a/drivers/pwm/pwm_th1520.rs
+++ b/drivers/pwm/pwm_th1520.rs
@@ -316,6 +316,7 @@ impl platform::Driver for Th1520PwmPlatformDriver {
 
     fn probe<'bound>(
         pdev: &'bound platform::Device<Core<'_>>,
+        _tokens: platform::InitTokens<'bound>,
         _id_info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self, Error> + 'bound {
         let dev = pdev.as_ref();
diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs
index b75d692846a2..0032264fe72c 100644
--- a/rust/kernel/cpufreq.rs
+++ b/rust/kernel/cpufreq.rs
@@ -916,6 +916,7 @@ fn register_em(_policy: &mut Policy) {
 ///
 ///     fn probe<'bound>(
 ///         pdev: &'bound platform::Device<Core<'_>>,
+///         _tokens: platform::InitTokens<'bound>,
 ///         _id_info: Option<&'bound Self::IdInfo>,
 ///     ) -> impl PinInit<Self, Error> + 'bound {
 ///         cpufreq::Registration::<SampleDriver>::new_foreign_owned(pdev.as_ref())?;
diff --git a/rust/kernel/io/mem.rs b/rust/kernel/io/mem.rs
index 32a919099dcd..50dedd32d1a7 100644
--- a/rust/kernel/io/mem.rs
+++ b/rust/kernel/io/mem.rs
@@ -70,6 +70,7 @@ pub(crate) unsafe fn new(device: &'a Device<Bound>, resource: &'a Resource) -> S
     ///
     ///    fn probe<'bound>(
     ///       pdev: &'bound platform::Device<Core<'_>>,
+    ///       _tokens: platform::InitTokens<'bound>,
     ///       info: Option<&'bound Self::IdInfo>,
     ///    ) -> impl PinInit<Self, Error> + 'bound {
     ///       let offset = 0; // Some offset.
@@ -130,6 +131,7 @@ pub fn iomap_exclusive_sized<const SIZE: usize>(self) -> Result<ExclusiveIoMem<'
     ///
     ///    fn probe<'bound>(
     ///       pdev: &'bound platform::Device<Core<'_>>,
+    ///       _tokens: platform::InitTokens<'bound>,
     ///       info: Option<&'bound Self::IdInfo>,
     ///    ) -> impl PinInit<Self, Error> + 'bound {
     ///       let offset = 0; // Some offset.
diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs
index 04a6d240afb2..1d61fcb64b03 100644
--- a/rust/kernel/pci.rs
+++ b/rust/kernel/pci.rs
@@ -147,7 +147,7 @@ extern "C" fn probe_callback(
         let info = unsafe { id.info_unchecked_opt::<T::IdInfo>() };
 
         from_result(|| {
-            let data = T::probe(pdev, info);
+            let data = T::probe(pdev, InitTokens { _p: PhantomData }, info);
 
             pdev.as_ref().set_drvdata(data)?;
             Ok(0)
@@ -451,6 +451,12 @@ 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 ()>,
+}
+
 /// The PCI driver trait.
 ///
 /// # Examples
@@ -479,6 +485,7 @@ macro_rules! pci_device_table {
 ///
 ///     fn probe<'bound>(
 ///         _pdev: &'bound pci::Device<Core<'_>>,
+///         _tokens: pci::InitTokens<'bound>,
 ///         _id_info: Option<&'bound Self::IdInfo>,
 ///     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
 ///         Err(ENODEV)
@@ -513,6 +520,7 @@ pub trait Driver {
     /// attempt to initialize the device here.
     fn probe<'bound>(
         dev: &'bound Device<device::Core<'_>>,
+        tokens: InitTokens<'bound>,
         id_info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound;
 
diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs
index ac0a012ae1bb..a7b33e229a30 100644
--- a/rust/kernel/platform.rs
+++ b/rust/kernel/platform.rs
@@ -104,7 +104,7 @@ 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, info);
+            let data = T::probe(pdev, InitTokens { _p: PhantomData }, info);
 
             pdev.as_ref().set_drvdata(data)?;
             Ok(0)
@@ -159,6 +159,12 @@ 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 ()>,
+}
+
 /// The platform driver trait.
 ///
 /// Drivers must implement this trait in order to get a platform driver registered.
@@ -199,6 +205,7 @@ macro_rules! module_platform_driver {
 ///
 ///     fn probe<'bound>(
 ///         _pdev: &'bound platform::Device<Core<'_>>,
+///         _tokens: platform::InitTokens<'bound>,
 ///         _id_info: Option<&'bound Self::IdInfo>,
 ///     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
 ///         Err(ENODEV)
@@ -229,6 +236,7 @@ pub trait Driver {
     /// Implementers should attempt to initialize the device here.
     fn probe<'bound>(
         dev: &'bound Device<device::Core<'_>>,
+        tokens: InitTokens<'bound>,
         id_info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound;
 
diff --git a/samples/rust/rust_debugfs.rs b/samples/rust/rust_debugfs.rs
index 77c19a437695..d0cc2b624835 100644
--- a/samples/rust/rust_debugfs.rs
+++ b/samples/rust/rust_debugfs.rs
@@ -122,6 +122,7 @@ impl platform::Driver for RustDebugFs {
 
     fn probe<'bound>(
         pdev: &'bound platform::Device<Core<'_>>,
+        _tokens: platform::InitTokens<'bound>,
         _info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self, Error> + 'bound {
         RustDebugFs::new(pdev).pin_chain(|this| {
diff --git a/samples/rust/rust_dma.rs b/samples/rust/rust_dma.rs
index 804d55a63005..b6a36d10bf74 100644
--- a/samples/rust/rust_dma.rs
+++ b/samples/rust/rust_dma.rs
@@ -77,6 +77,7 @@ impl pci::Driver for DmaSampleDriver {
 
     fn probe<'bound>(
         pdev: &'bound pci::Device<Core<'_>>,
+        _tokens: pci::InitTokens<'bound>,
         _info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
         pin_init::pin_init_scope(move || {
diff --git a/samples/rust/rust_driver_auxiliary.rs b/samples/rust/rust_driver_auxiliary.rs
index 6cff9bf8c80c..96954f001b13 100644
--- a/samples/rust/rust_driver_auxiliary.rs
+++ b/samples/rust/rust_driver_auxiliary.rs
@@ -99,6 +99,7 @@ impl pci::Driver for ParentDriver {
 
     fn probe<'bound>(
         pdev: &'bound pci::Device<Core<'_>>,
+        _tokens: pci::InitTokens<'bound>,
         _info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
         try_pin_init!(ParentData {
diff --git a/samples/rust/rust_driver_pci.rs b/samples/rust/rust_driver_pci.rs
index 50c8709739c6..33b864d2cbea 100644
--- a/samples/rust/rust_driver_pci.rs
+++ b/samples/rust/rust_driver_pci.rs
@@ -148,6 +148,7 @@ impl pci::Driver for SampleDriver {
 
     fn probe<'bound>(
         pdev: &'bound pci::Device<Core<'_>>,
+        _tokens: pci::InitTokens<'bound>,
         info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
         let vendor = pdev.vendor_id();
diff --git a/samples/rust/rust_driver_platform.rs b/samples/rust/rust_driver_platform.rs
index 710145b3605a..80b08d32435f 100644
--- a/samples/rust/rust_driver_platform.rs
+++ b/samples/rust/rust_driver_platform.rs
@@ -105,6 +105,7 @@ impl platform::Driver for SampleDriver {
 
     fn probe<'bound>(
         pdev: &'bound platform::Device<Core<'_>>,
+        _tokens: platform::InitTokens<'bound>,
         info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self, Error> + 'bound {
         let dev = pdev.as_ref();
diff --git a/samples/rust/rust_driver_sriov/pf.rs b/samples/rust/rust_driver_sriov/pf.rs
index 8f9958683528..3df204c9951c 100644
--- a/samples/rust/rust_driver_sriov/pf.rs
+++ b/samples/rust/rust_driver_sriov/pf.rs
@@ -69,6 +69,7 @@ impl pci::Driver for SamplePfDriver {
 
     fn probe<'bound>(
         pdev: &'bound pci::Device<Core<'_>>,
+        _tokens: pci::InitTokens<'bound>,
         _info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
         try_pin_init!(PfDriverData {
diff --git a/samples/rust/rust_driver_sriov/vf.rs b/samples/rust/rust_driver_sriov/vf.rs
index 256b1b3dfab7..c4bfca1a1c31 100644
--- a/samples/rust/rust_driver_sriov/vf.rs
+++ b/samples/rust/rust_driver_sriov/vf.rs
@@ -31,6 +31,7 @@ impl pci::Driver for SampleVfDriver {
 
     fn probe<'bound>(
         pdev: &'bound pci::Device<Core<'_>>,
+        _tokens: pci::InitTokens<'bound>,
         _info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self, Error> + 'bound {
         dev_info!(
diff --git a/samples/rust/rust_i2c_client.rs b/samples/rust/rust_i2c_client.rs
index c8a23875ef5b..93b207699860 100644
--- a/samples/rust/rust_i2c_client.rs
+++ b/samples/rust/rust_i2c_client.rs
@@ -110,6 +110,7 @@ impl platform::Driver for SampleDriver {
 
     fn probe<'bound>(
         pdev: &'bound platform::Device<device::Core<'_>>,
+        _tokens: platform::InitTokens<'bound>,
         _info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self, Error> + 'bound {
         dev_info!(
diff --git a/samples/rust/rust_soc.rs b/samples/rust/rust_soc.rs
index f5e5f2f9adf7..f54c173fed94 100644
--- a/samples/rust/rust_soc.rs
+++ b/samples/rust/rust_soc.rs
@@ -41,6 +41,7 @@ impl platform::Driver for SampleSocDriver {
 
     fn probe<'bound>(
         pdev: &'bound platform::Device<Core<'_>>,
+        _tokens: platform::InitTokens<'bound>,
         _info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self, Error> + 'bound {
         dev_dbg!(pdev, "Probe Rust SoC driver sample.\n");
-- 
2.51.2


^ permalink raw reply	[flat|nested] 11+ messages in thread

* [RFC PATCH v2 02/10] rust: dma: add Setup, Params and Handle
  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
  2026-11-29 22:24 ` [RFC PATCH v2 03/10] gpu: nova-core: configure DMA through dma::Setup Matteo Kloiber
                   ` (7 subsequent siblings)
  9 siblings, 0 replies; 11+ messages in thread
From: Matteo Kloiber @ 2026-11-29 22:24 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot, Alice Ryhl, Abdiel Janulgue,
	Robin Murphy, Andreas Hindborg, Gary Guo
  Cc: Daniel Almeida, Miguel Ojeda, David Airlie, Simona Vetter,
	Bjorn Helgaas, Krzysztof Wilczyński, Greg Kroah-Hartman,
	rust-for-linux, driver-core, dri-devel, nova-gpu, linux-kernel,
	Matteo Kloiber

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


^ permalink raw reply	[flat|nested] 11+ messages in thread

* [RFC PATCH v2 03/10] gpu: nova-core: configure DMA through dma::Setup
  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 ` [RFC PATCH v2 02/10] rust: dma: add Setup, Params and Handle Matteo Kloiber
@ 2026-11-29 22:24 ` Matteo Kloiber
  2026-11-29 22:24 ` [RFC PATCH v2 04/10] drm/tyr: " Matteo Kloiber
                   ` (6 subsequent siblings)
  9 siblings, 0 replies; 11+ messages in thread
From: Matteo Kloiber @ 2026-11-29 22:24 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot, Alice Ryhl, Abdiel Janulgue,
	Robin Murphy, Andreas Hindborg, Gary Guo
  Cc: Daniel Almeida, Miguel Ojeda, David Airlie, Simona Vetter,
	Bjorn Helgaas, Krzysztof Wilczyński, Greg Kroah-Hartman,
	rust-for-linux, driver-core, dri-devel, nova-gpu, linux-kernel,
	Matteo Kloiber

Gpu::new() sets the DMA mask and the maximum segment size with the
unsafe dma::Device setters, and relies on a comment to rule out
concurrent DMA allocations.

Take the dma::Setup token from the PCI InitTokens and configure DMA
through it instead, with the same mask and the same unlimited segment
size. Store the returned dma::Handle in Gpu, so that the fields
initialized after it can use it, and keep a copy in GspResources for
the GSP unload path.

Pass the handle instead of the device to everything that allocates or
maps DMA memory. The DMA APIs still take a device, so hand them
dma.device() for now. They are converted to take the handle once all
drivers have one.

No functional change intended.

Suggested-by: Danilo Krummrich <dakr@kernel.org>
Signed-off-by: Matteo Kloiber <kernel@matt3o12.de>
---
 drivers/gpu/nova-core/driver.rs               |  5 +-
 drivers/gpu/nova-core/falcon.rs               | 13 +++--
 drivers/gpu/nova-core/fb.rs                   | 11 +++--
 .../nova-core/firmware/fwsec/bootloader.rs    | 13 +++--
 drivers/gpu/nova-core/firmware/gsp.rs         | 19 ++++----
 drivers/gpu/nova-core/firmware/gsp_fmc.rs     | 10 ++--
 drivers/gpu/nova-core/firmware/radix3.rs      | 12 ++---
 drivers/gpu/nova-core/firmware/riscv.rs       | 11 +++--
 drivers/gpu/nova-core/fsp.rs                  | 20 ++++----
 drivers/gpu/nova-core/gpu.rs                  | 47 ++++++++++++-------
 drivers/gpu/nova-core/gsp.rs                  | 19 ++++----
 drivers/gpu/nova-core/gsp/boot.rs             |  2 +-
 drivers/gpu/nova-core/gsp/cmdq.rs             | 14 +++---
 drivers/gpu/nova-core/gsp/hal/gh100.rs        |  9 ++--
 drivers/gpu/nova-core/gsp/hal/tu102.rs        | 24 ++++++----
 drivers/gpu/nova-core/gsp/logbuffer.rs        | 23 +++++----
 16 files changed, 145 insertions(+), 107 deletions(-)

diff --git a/drivers/gpu/nova-core/driver.rs b/drivers/gpu/nova-core/driver.rs
index 365e77ff0cc4..fbbb4f4fa55b 100644
--- a/drivers/gpu/nova-core/driver.rs
+++ b/drivers/gpu/nova-core/driver.rs
@@ -101,9 +101,10 @@ impl pci::Driver for NovaCoreDriver {
 
     fn probe<'bound>(
         pdev: &'bound pci::Device<Core<'_>>,
-        _tokens: pci::InitTokens<'bound>,
+        tokens: pci::InitTokens<'bound>,
         _info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
+        let pci::InitTokens { dma: setup, .. } = tokens;
         dev_dbg!(pdev, "Probe Nova Core GPU driver.\n");
 
         try_pin_init!(NovaCore {
@@ -133,7 +134,7 @@ fn probe<'bound>(
                 crate::irq::doorbell_test::run_selftest(pdev, bar, spec.chipset)?;
             },
 
-            gpu <- Gpu::new(pdev, bar, bar1).pin_chain(|_gpu| {
+            gpu <- Gpu::new(pdev, setup, bar, bar1).pin_chain(|_gpu| {
                 #[cfg(CONFIG_NOVA_CORE_SELFTESTS)]
                 _gpu.run_selftests(pdev);
                 Ok(())
diff --git a/drivers/gpu/nova-core/falcon.rs b/drivers/gpu/nova-core/falcon.rs
index 8bcc9240d1bd..c9ffda0208b0 100644
--- a/drivers/gpu/nova-core/falcon.rs
+++ b/drivers/gpu/nova-core/falcon.rs
@@ -7,6 +7,7 @@
 use kernel::{
     device,
     dma::{
+        self,
         Coherent,
         CoherentBox,
         DmaAddress, //
@@ -374,6 +375,7 @@ pub(crate) trait FalconFirmware {
 pub(crate) struct Falcon<'a, E: FalconEngine> {
     hal: KBox<dyn FalconHal<E>>,
     dev: &'a device::Device<device::Bound>,
+    dma: dma::Handle<'a>,
     bar: Bar0<'a>,
     pfalcon: Mmio<'a, PFalconRegisters>,
     pfalcon2: Mmio<'a, PFalcon2Registers>,
@@ -381,14 +383,11 @@ pub(crate) struct Falcon<'a, E: FalconEngine> {
 
 impl<'a, E: FalconEngine + 'static> Falcon<'a, E> {
     /// Create a new falcon instance.
-    pub(crate) fn new(
-        dev: &'a device::Device<device::Bound>,
-        chipset: Chipset,
-        bar: Bar0<'a>,
-    ) -> Result<Self> {
+    pub(crate) fn new(dma: dma::Handle<'a>, chipset: Chipset, bar: Bar0<'a>) -> Result<Self> {
         Ok(Self {
             hal: hal::falcon_hal(chipset)?,
-            dev,
+            dev: dma.device(),
+            dma,
             bar,
             pfalcon: E::pfalcon(bar),
             pfalcon2: E::pfalcon2(bar),
@@ -650,7 +649,7 @@ fn dma_load<F: FalconFirmware<Target = E> + FalconDmaLoadable>(&self, fw: &F) ->
             // DMA copies are done in chunks of `MEM_BLOCK_ALIGNMENT`, so pad the length
             // accordingly and fill with `0`.
             let mut dma_obj = CoherentBox::zeroed_slice(
-                self.dev,
+                self.dma.device(),
                 fw_slice.len().next_multiple_of(MEM_BLOCK_ALIGNMENT),
                 GFP_KERNEL,
             )?;
diff --git a/drivers/gpu/nova-core/fb.rs b/drivers/gpu/nova-core/fb.rs
index 5ceb7760c78e..a2505da09a79 100644
--- a/drivers/gpu/nova-core/fb.rs
+++ b/drivers/gpu/nova-core/fb.rs
@@ -7,7 +7,10 @@
 
 use kernel::{
     device,
-    dma::CoherentHandle,
+    dma::{
+        self,
+        CoherentHandle, //
+    },
     fmt,
     io::Io,
     prelude::*,
@@ -55,17 +58,17 @@ pub(crate) struct SysmemFlush<'sys> {
 impl<'sys> SysmemFlush<'sys> {
     /// Allocate a memory page and register it as the sysmem flush page.
     pub(crate) fn register(
-        dev: &'sys device::Device<device::Bound>,
+        dma: dma::Handle<'sys>,
         bar: Bar0<'sys>,
         chipset: Chipset,
     ) -> Result<Self> {
-        let page = CoherentHandle::alloc(dev, kernel::page::PAGE_SIZE, GFP_KERNEL)?;
+        let page = CoherentHandle::alloc(dma.device(), kernel::page::PAGE_SIZE, GFP_KERNEL)?;
 
         hal::fb_hal(chipset).write_sysmem_flush_page(bar, page.dma_address())?;
 
         Ok(Self {
             chipset,
-            device: dev,
+            device: dma.device(),
             bar,
             page,
         })
diff --git a/drivers/gpu/nova-core/firmware/fwsec/bootloader.rs b/drivers/gpu/nova-core/firmware/fwsec/bootloader.rs
index 461e5e6f7899..49651a404286 100644
--- a/drivers/gpu/nova-core/firmware/fwsec/bootloader.rs
+++ b/drivers/gpu/nova-core/firmware/fwsec/bootloader.rs
@@ -11,7 +11,10 @@
         self,
         Device, //
     },
-    dma::Coherent,
+    dma::{
+        self,
+        Coherent, //
+    },
     prelude::*, //
 };
 
@@ -45,14 +48,14 @@ pub(crate) struct FwsecFirmwareWithBl<'a> {
 }
 
 impl<'a> FwsecFirmwareWithBl<'a> {
-    /// Loads the bootloader firmware for `dev` and `chipset`, and wrap `firmware` so it can be
+    /// Loads the bootloader firmware for the device and `chipset`, and wrap `firmware` so it can be
     /// loaded using it.
     pub(crate) fn new(
         firmware: FwsecFirmware,
-        dev: &'a Device<device::Bound>,
+        dma: dma::Handle<'a>,
         chipset: Chipset,
     ) -> Result<Self> {
-        let bootloader = GenericBootloader::new(dev, chipset)?;
+        let bootloader = GenericBootloader::new(dma.device(), chipset)?;
 
         // `BootloaderDmemDescV2` expects the source to be a mirror image of the destination and
         // uses the same offset parameter for both.
@@ -77,7 +80,7 @@ pub(crate) fn new(
 
             (
                 align_padding,
-                Coherent::from_slice(dev, firmware_obj.as_slice(), GFP_KERNEL)?,
+                Coherent::from_slice(dma.device(), firmware_obj.as_slice(), GFP_KERNEL)?,
             )
         };
 
diff --git a/drivers/gpu/nova-core/firmware/gsp.rs b/drivers/gpu/nova-core/firmware/gsp.rs
index 341a8b19aa38..e5fce91337a8 100644
--- a/drivers/gpu/nova-core/firmware/gsp.rs
+++ b/drivers/gpu/nova-core/firmware/gsp.rs
@@ -1,8 +1,8 @@
 // SPDX-License-Identifier: GPL-2.0
 
 use kernel::{
-    device,
     dma::{
+        self,
         Coherent,
         DmaAddress, //
     },
@@ -37,12 +37,10 @@ pub(crate) struct GspFirmware<'a> {
 }
 
 impl<'a> GspFirmware<'a> {
-    /// Loads the GSP firmware binaries, map them into `dev`'s address-space, and creates the page
-    /// tables expected by the GSP bootloader to load it.
-    pub(crate) fn new(
-        dev: &'a device::Device<device::Bound>,
-        chipset: Chipset,
-    ) -> impl PinInit<Self, Error> + 'a {
+    /// Loads the GSP firmware binaries, maps them into the device's address space, and creates
+    /// the page tables expected by the GSP bootloader to load it.
+    pub(crate) fn new(dma: dma::Handle<'a>, chipset: Chipset) -> impl PinInit<Self, Error> + 'a {
+        let dev = dma.device();
         pin_init::pin_init_scope(move || {
             let firmware = request_tlv(dev, chipset, "gsp")?;
             let tlv = Tlv::new(firmware.data())?;
@@ -56,15 +54,16 @@ pub(crate) fn new(
             let filename = CString::try_from_fmt(fmt!("nvidia/{chip_name}/gsp/{file}"))?;
             firmware::request_into_buf(&filename, dev, fw_vvec.as_mut_slice())?;
 
-            let signatures = Coherent::from_slice(dev, tlv.get_bytes(b"SIGN")?, GFP_KERNEL)?;
+            let signatures =
+                Coherent::from_slice(dma.device(), tlv.get_bytes(b"SIGN")?, GFP_KERNEL)?;
 
             Ok(try_pin_init!(Self {
-                radix3 <- Radix3::new(dev, fw_vvec),
+                radix3 <- Radix3::new(dma, fw_vvec),
                 signatures,
                 bootloader: {
                     let bl = request_tlv(dev, chipset, "gsp_bootloader")?;
 
-                    RiscvFirmware::new(dev, &bl)?
+                    RiscvFirmware::new(dma, &bl)?
                 },
             }))
         })
diff --git a/drivers/gpu/nova-core/firmware/gsp_fmc.rs b/drivers/gpu/nova-core/firmware/gsp_fmc.rs
index 94fcc86c7dff..230d631beaf4 100644
--- a/drivers/gpu/nova-core/firmware/gsp_fmc.rs
+++ b/drivers/gpu/nova-core/firmware/gsp_fmc.rs
@@ -6,7 +6,10 @@
 
 use kernel::{
     device,
-    dma::Coherent,
+    dma::{
+        self,
+        Coherent, //
+    },
     prelude::*, //
 };
 
@@ -48,7 +51,8 @@ pub(crate) struct GspFmcFirmware<'a> {
 }
 
 impl<'a> GspFmcFirmware<'a> {
-    pub(crate) fn new(dev: &'a device::Device<device::Bound>, chipset: Chipset) -> Result<Self> {
+    pub(crate) fn new(dma: dma::Handle<'a>, chipset: Chipset) -> Result<Self> {
+        let dev = dma.device();
         let fw = request_tlv(dev, chipset, "fmc")?;
         let tlv = Tlv::new(fw.data())?;
         dev_dbg!(
@@ -58,7 +62,7 @@ pub(crate) fn new(dev: &'a device::Device<device::Bound>, chipset: Chipset) -> R
         );
 
         let fmc_image_data = tlv.get_bytes(b"BLOB")?;
-        let fmc_image = Coherent::from_slice(dev, fmc_image_data, GFP_KERNEL)?;
+        let fmc_image = Coherent::from_slice(dma.device(), fmc_image_data, GFP_KERNEL)?;
 
         Ok(Self {
             fmc_image,
diff --git a/drivers/gpu/nova-core/firmware/radix3.rs b/drivers/gpu/nova-core/firmware/radix3.rs
index 94235bd1209d..5e10263e8313 100644
--- a/drivers/gpu/nova-core/firmware/radix3.rs
+++ b/drivers/gpu/nova-core/firmware/radix3.rs
@@ -12,8 +12,8 @@
 //! ```
 
 use kernel::{
-    device,
     dma::{
+        self,
         Coherent,
         CoherentBox,
         DataDirection,
@@ -50,11 +50,9 @@ pub(crate) struct Radix3<'a> {
 }
 
 impl<'a> Radix3<'a> {
-    /// Builds a radix3 page table over `data`, mapped for `dev` to read. May sleep.
-    pub(crate) fn new(
-        dev: &'a device::Device<device::Bound>,
-        data: VVec<u8>,
-    ) -> impl PinInit<Self, Error> + 'a {
+    /// Builds a radix3 page table over `data`, mapped for the device to read. May sleep.
+    pub(crate) fn new(dma: dma::Handle<'a>, data: VVec<u8>) -> impl PinInit<Self, Error> + 'a {
+        let dev = dma.device();
         let size = data.len();
 
         pin_init::pin_init_scope(move || {
@@ -79,7 +77,7 @@ pub(crate) fn new(
                     // Create level 0 page table data and fill its first entry with the level 1
                     // table.
                     let mut level0 = CoherentBox::<'_, [u64]>::zeroed_slice(
-                        dev,
+                        dma.device(),
                         GSP_PAGE_SIZE / size_of::<u64>(),
                         GFP_KERNEL
                     )?;
diff --git a/drivers/gpu/nova-core/firmware/riscv.rs b/drivers/gpu/nova-core/firmware/riscv.rs
index f05cfb1c65da..ce0da2efe34e 100644
--- a/drivers/gpu/nova-core/firmware/riscv.rs
+++ b/drivers/gpu/nova-core/firmware/riscv.rs
@@ -4,8 +4,10 @@
 //! dedicated header.
 
 use kernel::{
-    device,
-    dma::Coherent,
+    dma::{
+        self,
+        Coherent, //
+    },
     firmware::Firmware,
     prelude::*, //
 };
@@ -28,7 +30,8 @@ pub(crate) struct RiscvFirmware<'a> {
 
 impl<'a> RiscvFirmware<'a> {
     /// Parses the RISC-V firmware image contained in `fw`.
-    pub(crate) fn new(dev: &'a device::Device<device::Bound>, fw: &Firmware) -> Result<Self> {
+    pub(crate) fn new(dma: dma::Handle<'a>, fw: &Firmware) -> Result<Self> {
+        let dev = dma.device();
         let tlv = Tlv::new(fw.data())?;
         dev_dbg!(
             dev,
@@ -41,7 +44,7 @@ pub(crate) fn new(dev: &'a device::Device<device::Bound>, fw: &Firmware) -> Resu
         let manifest_offset = tlv.get_u32(b"MFOF")?;
         let app_version = tlv.get_u32(b"APPV")?;
 
-        let ucode = Coherent::from_slice(dev, tlv.get_bytes(b"BLOB")?, GFP_KERNEL)?;
+        let ucode = Coherent::from_slice(dma.device(), tlv.get_bytes(b"BLOB")?, GFP_KERNEL)?;
 
         Ok(Self {
             ucode,
diff --git a/drivers/gpu/nova-core/fsp.rs b/drivers/gpu/nova-core/fsp.rs
index ea08cd58346f..17da2efbf0e0 100644
--- a/drivers/gpu/nova-core/fsp.rs
+++ b/drivers/gpu/nova-core/fsp.rs
@@ -12,7 +12,10 @@
 
 use kernel::{
     device,
-    dma::Coherent,
+    dma::{
+        self,
+        Coherent, //
+    },
     io::poll::read_poll_timeout,
     num::TryIntoBounded,
     prelude::*,
@@ -359,7 +362,7 @@ impl<'a> FmcBootArgs<'a> {
     /// Builds FMC boot arguments, allocating the DMA-coherent boot parameter
     /// structure that FSP will read.
     pub(crate) fn new(
-        dev: &'a device::Device<device::Bound>,
+        dma: dma::Handle<'a>,
         chipset: Chipset,
         wpr_meta: Coherent<'a, GspFwWprMeta>,
         libos: &'a Coherent<'a, [LibosMemoryRegionInitArgument]>,
@@ -369,7 +372,7 @@ pub(crate) fn new(
 
         Ok(Self {
             chipset,
-            fmc_boot_params: Coherent::init(dev, GFP_KERNEL, init)?,
+            fmc_boot_params: Coherent::init(dma.device(), GFP_KERNEL, init)?,
             resume,
             _wpr_meta: wpr_meta,
             _libos: libos,
@@ -401,13 +404,13 @@ impl<'a> Fsp<'a> {
     ///
     /// If `chipset` doesn't support FSP, `Ok(None)` is returned.
     pub(crate) fn try_new(
-        dev: &'a device::Device<device::Bound>,
+        dma: dma::Handle<'a>,
         bar: Bar0<'a>,
         chipset: Chipset,
     ) -> Result<Option<Self>> {
         match hal::fsp_hal(chipset) {
             None => Ok(None),
-            Some(hal) => Self::wait_secure_boot(dev, bar, chipset, hal).map(Option::Some),
+            Some(hal) => Self::wait_secure_boot(dma, bar, chipset, hal).map(Option::Some),
         }
     }
 
@@ -417,7 +420,7 @@ pub(crate) fn try_new(
     /// elapses. Returning an [`Fsp`] only on success guarantees, at the API level, that the
     /// interface is not used before secure boot has completed.
     fn wait_secure_boot(
-        dev: &'a device::Device<device::Bound>,
+        dma: dma::Handle<'a>,
         bar: Bar0<'a>,
         chipset: Chipset,
         hal: &'static dyn hal::FspHal,
@@ -425,8 +428,9 @@ fn wait_secure_boot(
         /// FSP secure boot completion timeout in milliseconds.
         const FSP_SECURE_BOOT_TIMEOUT_MS: i64 = 5000;
 
-        let falcon = Falcon::<FspEngine>::new(dev, chipset, bar)?;
-        let fmc_fw = GspFmcFirmware::new(dev, chipset)?;
+        let dev = dma.device();
+        let falcon = Falcon::<FspEngine>::new(dma, chipset, bar)?;
+        let fmc_fw = GspFmcFirmware::new(dma, chipset)?;
 
         read_poll_timeout(
             || Ok(hal.fsp_boot_status(bar)),
diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
index 8ab1687847ff..2a59948169ef 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -1,10 +1,13 @@
 // SPDX-License-Identifier: GPL-2.0
 
-use core::ops::Range;
+use core::{
+    num::NonZeroU32,
+    ops::Range, //
+};
 
 use kernel::{
     device,
-    dma::Device,
+    dma,
     fmt,
     gpu::buddy::GpuBuddyParams,
     io::Io,
@@ -322,6 +325,8 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 struct GspResources<'gpu> {
     /// Device owning the GPU.
     device: &'gpu pci::Device<device::Bound>,
+    /// DMA handle used for the GPU's allocations.
+    dma: dma::Handle<'gpu>,
     /// Details about the chipset.
     spec: Spec,
     /// MMIO mapping of PCI BAR 0.
@@ -385,6 +390,8 @@ unsafe fn new(
 #[pin_data]
 pub(crate) struct Gpu<'gpu> {
     pub(crate) spec: Spec,
+    /// DMA handle of the configured device, kept as a field for the other field initializers.
+    dma: dma::Handle<'gpu>,
     /// GSP event interrupt registration, and the enable of its subtree.
     ///
     /// Must be kept declared *before* `gsp_resources`, so that the handler is unregistered, and
@@ -434,6 +441,7 @@ fn drop(self: Pin<&mut Self>) {
             .unload(
                 GspBootContext {
                     pdev: device,
+                    dma: *this.dma,
                     bar,
                     chipset: this.spec.chipset,
                     gsp_falcon: &*this.gsp_falcon,
@@ -450,6 +458,7 @@ fn drop(self: Pin<&mut Self>) {
 impl<'gpu> Gpu<'gpu> {
     pub(crate) fn new<'a>(
         pdev: &'gpu pci::Device<device::Core<'a>>,
+        setup: dma::Setup<'gpu>,
         bar: Bar0<'gpu>,
         bar1: Bar1<'gpu>,
     ) -> impl PinInit<Self, Error> + use<'gpu, 'a> {
@@ -462,51 +471,53 @@ pub(crate) fn new<'a>(
 
             tree: Tree::new(pdev, bar, spec.chipset, irq::gsp::GSP_SUBTREE.into())?,
 
-            _: {
+            dma: {
                 let dma_mask = hal::gpu_hal(spec.chipset).dma_mask();
 
-                // SAFETY: `Gpu` owns all DMA allocations for this device, and we are
-                // still constructing it, so no concurrent DMA allocations can exist.
-                unsafe { pdev.dma_set_mask_and_coherent(dma_mask)? };
-
-                // Nova walks SG segments to build page tables, so their length is
-                // irrelevant to the device.
-                //
-                // SAFETY: `Gpu` owns all DMA allocations for this device, and we are
-                // still constructing it, so no concurrent DMA allocations can exist.
-                unsafe { pdev.dma_set_max_seg_size(u32::MAX) };
+                setup.configure(dma::Params {
+                    streaming_mask: Some(dma_mask),
+                    coherent_mask: Some(dma_mask),
+                    // Nova walks SG segments to build page tables, so their length is
+                    // irrelevant to the device.
+                    max_seg_size: Some(NonZeroU32::MAX),
+                })?
+            },
 
+            _: {
                 // We must wait for GFW_BOOT completion before doing any significant setup on the GPU.
                 Self::wait_gfw_boot_completion(dev, bar, spec.chipset)?;
             },
 
             // Initialize this early because `gsp_resources` depends on it.
-            sysmem_flush: SysmemFlush::register(dev, bar, spec.chipset)?,
+            sysmem_flush: SysmemFlush::register(*dma, bar, spec.chipset)?,
 
             gsp_resources <- try_pin_init!(GspResources {
                 device: pdev,
 
+                dma: *dma,
+
                 spec: *spec,
 
                 bar,
 
-                gsp_falcon: Falcon::new(dev, spec.chipset, bar)?,
+                gsp_falcon: Falcon::new(*dma, spec.chipset, bar)?,
 
-                sec2_falcon: Falcon::new(dev, spec.chipset, bar)?,
+                sec2_falcon: Falcon::new(*dma, spec.chipset, bar)?,
 
-                fsp: Fsp::try_new(dev, bar, spec.chipset)?,
+                fsp: Fsp::try_new(*dma, bar, spec.chipset)?,
 
                 timer: Timer::setup(dev, bar, spec.chipset, fsp.as_ref())?,
 
                 vgpu: VgpuManager::new(pdev, spec.chipset, fsp.as_mut()),
 
-                gsp <- Gsp::new(pdev, bar),
+                gsp <- Gsp::new(*dma, bar),
 
                 // This member must be initialized last, so the `UnloadBundle` can never be dropped
                 // from outside of the constructed `GspResources`, ensuring that the unload sequence
                 // is properly run in case of failure.
                 unload_bundle: gsp.boot(GspBootContext {
                     pdev,
+                    dma: *dma,
                     bar,
                     chipset: spec.chipset,
                     gsp_falcon,
diff --git a/drivers/gpu/nova-core/gsp.rs b/drivers/gpu/nova-core/gsp.rs
index 2f1cdf8b7bec..908ecfbcd2aa 100644
--- a/drivers/gpu/nova-core/gsp.rs
+++ b/drivers/gpu/nova-core/gsp.rs
@@ -7,6 +7,7 @@
     debugfs,
     device,
     dma::{
+        self,
         Coherent,
         CoherentBox,
         CoherentView,
@@ -64,6 +65,7 @@
 /// - `'ctx` is a shorter lifetime during which this context borrows those subdevices.
 pub(crate) struct GspBootContext<'ctx, 'gpu> {
     pub(crate) pdev: &'gpu pci::Device<device::Bound>,
+    pub(crate) dma: dma::Handle<'gpu>,
     pub(crate) bar: Bar0<'gpu>,
     pub(crate) chipset: Chipset,
     pub(crate) gsp_falcon: &'ctx Falcon<'gpu, GspFalcon>,
@@ -114,25 +116,20 @@ pub(crate) struct Gsp<'gsp> {
 }
 
 impl<'gsp> Gsp<'gsp> {
-    // Creates an in-place initializer for a `Gsp` manager for `pdev`.
-    pub(crate) fn new(
-        pdev: &'gsp pci::Device<device::Bound>,
-        bar: Bar0<'gsp>,
-    ) -> impl PinInit<Self, Error> + 'gsp {
+    // Creates an in-place initializer for a `Gsp` manager for the device.
+    pub(crate) fn new(dma: dma::Handle<'gsp>, bar: Bar0<'gsp>) -> impl PinInit<Self, Error> + 'gsp {
         pin_init::pin_init_scope(move || {
-            let dev = pdev.as_ref();
-
-            let log_buffers = LogBuffers::new(dev)?;
+            let log_buffers = LogBuffers::new(dma)?;
 
             // Initialise the logging structures. The OpenRM equivalents are in:
             // _kgspInitLibosLoggingStructures (allocates memory for buffers)
             // kgspSetupLibosInitArgs_IMPL (creates pLibosInitArgs[] array)
             Ok(try_pin_init!(Self {
-                cmdq <- Cmdq::new(dev, bar),
-                rmargs: Coherent::init(dev, GFP_KERNEL, GspArgumentsPadded::new(&cmdq))?,
+                cmdq <- Cmdq::new(dma, bar),
+                rmargs: Coherent::init(dma.device(), GFP_KERNEL, GspArgumentsPadded::new(&cmdq))?,
                 libos: {
                     let mut libos = CoherentBox::zeroed_slice(
-                        dev,
+                        dma.device(),
                         GSP_PAGE_SIZE / size_of::<LibosMemoryRegionInitArgument>(),
                         GFP_KERNEL,
                     )?;
diff --git a/drivers/gpu/nova-core/gsp/boot.rs b/drivers/gpu/nova-core/gsp/boot.rs
index 9d5da5b165ac..fc24a779305f 100644
--- a/drivers/gpu/nova-core/gsp/boot.rs
+++ b/drivers/gpu/nova-core/gsp/boot.rs
@@ -39,7 +39,7 @@ pub(crate) fn boot(
         let dev = pdev.as_ref();
         let hal = super::hal::gsp_hal(chipset);
 
-        let gsp_fw = KBox::pin_init(GspFirmware::new(dev, chipset), GFP_KERNEL)?;
+        let gsp_fw = KBox::pin_init(GspFirmware::new(ctx.dma, chipset), GFP_KERNEL)?;
 
         self.cmdq
             .send_rpc_command_no_wait(commands::rpc::SetSystemInfo::new(
diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/cmdq.rs
index e2b9a5383a66..d34174998f3d 100644
--- a/drivers/gpu/nova-core/gsp/cmdq.rs
+++ b/drivers/gpu/nova-core/gsp/cmdq.rs
@@ -12,6 +12,7 @@
 use kernel::{
     device,
     dma::{
+        self,
         Coherent,
         CoherentBox,
         DmaAddress, //
@@ -174,12 +175,12 @@ struct DmaGspMem<'a> {
 }
 
 impl<'a> DmaGspMem<'a> {
-    /// Allocate a new instance and map it for `dev`.
-    fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> {
+    /// Allocate a new instance and map it for the device.
+    fn new(dma: dma::Handle<'a>, bar: Bar0<'a>) -> Result<Self> {
         const MSGQ_SIZE: u32 = cv!(size_of::<Msgq>());
         const RX_HDR_OFF: u32 = cv!(mem::offset_of!(Msgq, rx));
 
-        let mut gsp_mem = CoherentBox::<'_, GspMem>::zeroed(dev, GFP_KERNEL)?;
+        let mut gsp_mem = CoherentBox::<'_, GspMem>::zeroed(dma.device(), GFP_KERNEL)?;
         gsp_mem.cpuq.tx = MsgqTxHeader::new(MSGQ_SIZE, RX_HDR_OFF, MSGQ_NUM_PAGES);
         gsp_mem.cpuq.rx = MsgqRxHeader::new();
 
@@ -489,13 +490,14 @@ impl<'cmdq> Cmdq<'cmdq> {
     /// Default timeout for receiving a message from the GSP.
     pub(super) const RECEIVE_TIMEOUT: Delta = Delta::from_secs(5);
 
-    /// Creates a new command queue for `dev`.
+    /// Creates a new command queue for the device.
     pub(crate) fn new(
-        dev: &'cmdq device::Device<device::Bound>,
+        dma: dma::Handle<'cmdq>,
         bar: Bar0<'cmdq>,
     ) -> impl PinInit<Self, Error> + 'cmdq {
         pin_init_scope(move || {
-            let gsp_mem = DmaGspMem::new(dev, bar)?;
+            let dev = dma.device();
+            let gsp_mem = DmaGspMem::new(dma, bar)?;
 
             Ok(try_pin_init!(Self {
                 dma_addr: gsp_mem.mem.dma_address(),
diff --git a/drivers/gpu/nova-core/gsp/hal/gh100.rs b/drivers/gpu/nova-core/gsp/hal/gh100.rs
index 91201b51030e..f194df6656aa 100644
--- a/drivers/gpu/nova-core/gsp/hal/gh100.rs
+++ b/drivers/gpu/nova-core/gsp/hal/gh100.rs
@@ -154,9 +154,12 @@ fn boot<'gpu>(
         let fb_sizes = FbSizes::new(chipset, ctx.bar, ctx.vgpu.state())?;
         dev_dbg!(dev, "{:#x?}\n", fb_sizes);
 
-        let wpr_meta =
-            Coherent::init(dev, GFP_KERNEL, GspFwWprMeta::from_sizes(gsp_fw, &fb_sizes))?;
-        let args = FmcBootArgs::new(dev, chipset, wpr_meta, &gsp.libos, false)?;
+        let wpr_meta = Coherent::init(
+            ctx.dma.device(),
+            GFP_KERNEL,
+            GspFwWprMeta::from_sizes(gsp_fw, &fb_sizes),
+        )?;
+        let args = FmcBootArgs::new(ctx.dma, chipset, wpr_meta, &gsp.libos, false)?;
 
         let unload_bundle = crate::gsp::UnloadBundle(
             KBox::new(FspUnloadBundle, GFP_KERNEL)? as KBox<dyn UnloadBundle + 'gpu>
diff --git a/drivers/gpu/nova-core/gsp/hal/tu102.rs b/drivers/gpu/nova-core/gsp/hal/tu102.rs
index 2139279d40c4..44a758335118 100644
--- a/drivers/gpu/nova-core/gsp/hal/tu102.rs
+++ b/drivers/gpu/nova-core/gsp/hal/tu102.rs
@@ -5,7 +5,10 @@
 
 use kernel::{
     device,
-    dma::Coherent,
+    dma::{
+        self,
+        Coherent, //
+    },
     io::Io,
     types::ScopeGuard, //
 };
@@ -136,13 +139,15 @@ impl Tu102 {
     /// created the WPR2 region.
     fn run_fwsec_frts(
         &self,
-        dev: &device::Device<device::Bound>,
+        dma: dma::Handle<'_>,
         chipset: Chipset,
         falcon: &Falcon<'_, GspEngine>,
         bar: Bar0<'_>,
         bios: &Vbios,
         fb_ranges: &FbRanges,
     ) -> Result {
+        let dev = dma.device();
+
         // Check that the WPR2 region does not already exist - if it does, we cannot run
         // FWSEC-FRTS until the GPU is reset.
         if wpr2_range(bar).is_some() {
@@ -165,7 +170,7 @@ fn run_fwsec_frts(
         )?;
 
         if self.needs_fwsec_bootloader {
-            let fwsec_frts_bl = FwsecFirmwareWithBl::new(fwsec_frts, dev, chipset)?;
+            let fwsec_frts_bl = FwsecFirmwareWithBl::new(fwsec_frts, dma, chipset)?;
             // Load and run the bootloader, which will load FWSEC-FRTS and run it.
             fwsec_frts_bl.run(dev, falcon)?;
         } else {
@@ -214,16 +219,18 @@ fn run_fwsec_frts(
     /// Load and prepare the resources required to properly reset the GSP after it has been stopped.
     fn build_unload_bundle<'gpu>(
         &self,
-        dev: &'gpu device::Device<device::Bound>,
+        dma: dma::Handle<'gpu>,
         chipset: Chipset,
         bios: &Vbios,
         gsp_falcon: &Falcon<'_, GspEngine>,
         sec2_falcon: &Falcon<'_, Sec2>,
     ) -> Result<crate::gsp::UnloadBundle<'gpu>> {
+        let dev = dma.device();
+
         // Load the FWSEC SB firmware, as well as its bootloader if required.
         let fwsec_sb = FwsecFirmware::new(dev, gsp_falcon, bios, FwsecCommand::Sb)?;
         let fwsec_sb = if self.needs_fwsec_bootloader {
-            FwsecUnloadFirmware::WithBl(FwsecFirmwareWithBl::new(fwsec_sb, dev, chipset)?)
+            FwsecUnloadFirmware::WithBl(FwsecFirmwareWithBl::new(fwsec_sb, dma, chipset)?)
         } else {
             FwsecUnloadFirmware::WithoutBl(fwsec_sb)
         };
@@ -252,6 +259,7 @@ fn boot<'gpu>(
         ctx: &mut GspBootContext<'_, 'gpu>,
         gsp_fw: &GspFirmware<'gpu>,
     ) -> Result<Option<crate::gsp::UnloadBundle<'gpu>>> {
+        let dma = ctx.dma;
         let dev = ctx.dev();
         let bar = ctx.bar;
         let chipset = ctx.chipset;
@@ -264,7 +272,7 @@ fn boot<'gpu>(
         // Declared before the unload guard so that if Booter fails while running, SEC2 is reset
         // by the guard before this allocation is freed.
         let wpr_meta = Coherent::init(
-            dev,
+            dma.device(),
             GFP_KERNEL,
             GspFwWprMeta::from_ranges(gsp_fw, &fb_ranges),
         )?;
@@ -276,7 +284,7 @@ fn boot<'gpu>(
         // If the unload bundle creation fails, the GPU will need to be reset before the driver can
         // be probed again.
         let unload_bundle = self
-            .build_unload_bundle(dev, chipset, &bios, gsp_falcon, sec2_falcon)
+            .build_unload_bundle(dma, chipset, &bios, gsp_falcon, sec2_falcon)
             .inspect_err(|e| dev_warn!(dev, "Failed to prepare unload firmware: {:?}\n", e))
             .ok();
 
@@ -289,7 +297,7 @@ fn boot<'gpu>(
 
         // FWSEC-FRTS is not executed on chips where the FRTS region size is 0 (e.g. GA100).
         if !fb_ranges.frts.is_empty() {
-            self.run_fwsec_frts(dev, chipset, gsp_falcon, bar, &bios, &fb_ranges)?;
+            self.run_fwsec_frts(dma, chipset, gsp_falcon, bar, &bios, &fb_ranges)?;
         }
 
         gsp_falcon.reset()?;
diff --git a/drivers/gpu/nova-core/gsp/logbuffer.rs b/drivers/gpu/nova-core/gsp/logbuffer.rs
index 5455d990ffb4..57d063c15502 100644
--- a/drivers/gpu/nova-core/gsp/logbuffer.rs
+++ b/drivers/gpu/nova-core/gsp/logbuffer.rs
@@ -5,7 +5,10 @@
 use kernel::{
     debugfs,
     device,
-    dma::Coherent,
+    dma::{
+        self,
+        Coherent, //
+    },
     io::{
         io_project,
         Io, //
@@ -47,9 +50,9 @@
 pub(super) struct LogBuffer<'a>(pub(super) Coherent<'a, [u8; LOG_BUFFER_SIZE]>);
 
 impl<'a> LogBuffer<'a> {
-    /// Creates a new `LogBuffer` mapped on `dev`.
-    fn new(dev: &'a device::Device<device::Bound>) -> Result<Self> {
-        let obj = Self(Coherent::zeroed(dev, GFP_KERNEL)?);
+    /// Creates a new `LogBuffer` mapped on the device.
+    fn new(dma: dma::Handle<'a>) -> Result<Self> {
+        let obj = Self(Coherent::zeroed(dma.device(), GFP_KERNEL)?);
 
         let start_addr = obj.0.dma_address();
 
@@ -98,13 +101,13 @@ pub(super) struct LogBuffers<'a> {
 }
 
 impl<'a> LogBuffers<'a> {
-    /// Allocates the log buffers of `dev`.
-    pub(super) fn new(dev: &'a device::Device<device::Bound>) -> Result<Self> {
+    /// Allocates the log buffers of the device.
+    pub(super) fn new(dma: dma::Handle<'a>) -> Result<Self> {
         Ok(Self {
-            dev,
-            loginit: LogBuffer::new(dev)?,
-            logintr: LogBuffer::new(dev)?,
-            logrm: LogBuffer::new(dev)?,
+            dev: dma.device(),
+            loginit: LogBuffer::new(dma)?,
+            logintr: LogBuffer::new(dma)?,
+            logrm: LogBuffer::new(dma)?,
         })
     }
 
-- 
2.51.2


^ permalink raw reply	[flat|nested] 11+ messages in thread

* [RFC PATCH v2 04/10] drm/tyr: configure DMA through dma::Setup
  2026-11-29 22:24 [RFC PATCH v2 00/10] rust: dma: require device configuration before DMA Matteo Kloiber
                   ` (2 preceding siblings ...)
  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 ` Matteo Kloiber
  2026-11-29 22:24 ` [RFC PATCH v2 05/10] samples: rust: dma: " Matteo Kloiber
                   ` (5 subsequent siblings)
  9 siblings, 0 replies; 11+ messages in thread
From: Matteo Kloiber @ 2026-11-29 22:24 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot, Alice Ryhl, Abdiel Janulgue,
	Robin Murphy, Andreas Hindborg, Gary Guo
  Cc: Daniel Almeida, Miguel Ojeda, David Airlie, Simona Vetter,
	Bjorn Helgaas, Krzysztof Wilczyński, Greg Kroah-Hartman,
	rust-for-linux, driver-core, dri-devel, nova-gpu, linux-kernel,
	Matteo Kloiber

Tyr sets its DMA mask with the unsafe dma::Device setter.

Take the dma::Setup token from the platform InitTokens and configure
DMA through it instead, with the same mask. Pass None for the maximum
segment size to keep its current value. Panthor sets UINT_MAX for the
same hardware, so Tyr probably should too, but that is a behaviour
change for a separate patch.

Pass the returned dma::Handle to the firmware loader and the VM, which
create the IOMMU page table and map the GEM shmem SG tables. Both APIs
still take a device, so hand them dma.device() for now.

No functional change intended.

Signed-off-by: Matteo Kloiber <kernel@matt3o12.de>
---
 drivers/gpu/drm/tyr/driver.rs            | 19 ++++++++++------
 drivers/gpu/drm/tyr/fw.rs                | 11 +++++-----
 drivers/gpu/drm/tyr/mmu/address_space.rs |  7 +++---
 drivers/gpu/drm/tyr/vm.rs                | 28 +++++++++++++++---------
 4 files changed, 39 insertions(+), 26 deletions(-)

diff --git a/drivers/gpu/drm/tyr/driver.rs b/drivers/gpu/drm/tyr/driver.rs
index 7650ade4ad72..9b9c7bd0fc6a 100644
--- a/drivers/gpu/drm/tyr/driver.rs
+++ b/drivers/gpu/drm/tyr/driver.rs
@@ -12,7 +12,7 @@
         DeviceContext, //
     },
     dma::{
-        Device as DmaDevice,
+        self,
         DmaMask, //
     },
     drm,
@@ -119,9 +119,10 @@ impl platform::Driver for TyrPlatformDriver {
 
     fn probe<'bound>(
         pdev: &'bound platform::Device<Core<'_>>,
-        _tokens: platform::InitTokens<'bound>,
+        tokens: platform::InitTokens<'bound>,
         _info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
+        let platform::InitTokens { dma: setup, .. } = tokens;
         pin_init::pin_init_scope(move || {
             let core_clk = Clk::get(pdev.as_ref(), Some(c"core"))?;
             let stacks_clk = OptionalClk::get(pdev.as_ref(), Some(c"stacks"))?;
@@ -147,17 +148,21 @@ fn probe<'bound>(
             let pa_bits = MMU_FEATURES::from_raw(gpu_info.mmu_features)
                 .pa_bits()
                 .get();
-            // SAFETY: No concurrent DMA allocations or mappings can be made because
-            // the device is still being probed and therefore isn't being used by
-            // other threads of execution.
-            unsafe { pdev.dma_set_mask_and_coherent(DmaMask::try_new(pa_bits)?)? };
+            let mask = DmaMask::try_new(pa_bits)?;
+            let dma = setup.configure(dma::Params {
+                streaming_mask: Some(mask),
+                coherent_mask: Some(mask),
+                // TODO: Panthor calls `dma_set_max_seg_size(dev, UINT_MAX)`; Tyr probably wants
+                // `Some(NonZeroU32::MAX)` here as well.
+                max_seg_size: None,
+            })?;
 
             let unreg_dev = drm::UnregisteredDevice::<TyrDrmDriver>::new(pdev)?;
 
             let mmu = Mmu::new(pdev.as_ref(), iomem.as_arc_borrow(), &gpu_info)?;
 
             let firmware = Firmware::new(
-                pdev.as_ref(),
+                dma,
                 iomem.clone(),
                 &unreg_dev,
                 mmu.as_arc_borrow(),
diff --git a/drivers/gpu/drm/tyr/fw.rs b/drivers/gpu/drm/tyr/fw.rs
index aea151ff1f93..b4e9de26ead5 100644
--- a/drivers/gpu/drm/tyr/fw.rs
+++ b/drivers/gpu/drm/tyr/fw.rs
@@ -15,10 +15,8 @@
 
 use kernel::{
     bitfield,
-    device::{
-        Bound,
-        Device, //
-    },
+    device::Device,
+    dma,
     drm::{
         gem::BaseObject, //
     },
@@ -213,13 +211,14 @@ fn load(
 
     /// Load firmware and map sections into MCU VM.
     pub(crate) fn new(
-        dev: &'drm Device<Bound>,
+        dma: dma::Handle<'drm>,
         iomem: Arc<IoMem<'drm>>,
         ddev: &TyrDrmDevice,
         mmu: ArcBorrow<'_, Mmu<'drm>>,
         gpu_info: &GpuInfo,
     ) -> Result<Firmware<'drm>> {
-        let vm = Vm::new(dev, ddev, mmu, gpu_info)?;
+        let dev = dma.device();
+        let vm = Vm::new(dma, ddev, mmu, gpu_info)?;
         vm.activate()?;
 
         let result = (|| {
diff --git a/drivers/gpu/drm/tyr/mmu/address_space.rs b/drivers/gpu/drm/tyr/mmu/address_space.rs
index 76e3d2df6afd..de7dce8e9ee6 100644
--- a/drivers/gpu/drm/tyr/mmu/address_space.rs
+++ b/drivers/gpu/drm/tyr/mmu/address_space.rs
@@ -12,7 +12,8 @@
     device::{
         Bound,
         Device, //
-    }, //
+    },
+    dma,
     error::Result,
     io::{
         poll,
@@ -89,7 +90,7 @@ impl<'drm> VmAsData<'drm> {
     /// Creates VM address space data by initializing all of its fields.
     pub(crate) fn new<'a>(
         mmu: &'a Mmu<'drm>,
-        dev: &'drm Device<Bound>,
+        dma: dma::Handle<'drm>,
         va_bits: u32,
         pa_bits: u32,
     ) -> impl pin_init::PinInit<VmAsData<'drm>, Error> + 'a {
@@ -101,7 +102,7 @@ pub(crate) fn new<'a>(
             coherent_walk: false,
         };
 
-        let page_table_init = IoPageTable::new(dev, pt_config);
+        let page_table_init = IoPageTable::new(dma.device(), pt_config);
 
         try_pin_init!(Self {
             as_seat: LockedBy::new(&mmu.as_manager, Seat::NoSeat),
diff --git a/drivers/gpu/drm/tyr/vm.rs b/drivers/gpu/drm/tyr/vm.rs
index 1dd11b2b1253..8465d065dceb 100644
--- a/drivers/gpu/drm/tyr/vm.rs
+++ b/drivers/gpu/drm/tyr/vm.rs
@@ -15,6 +15,7 @@
         Bound,
         Device, //
     },
+    dma,
     drm::{
         gem::BaseObject,
         gpuvm::{
@@ -219,8 +220,10 @@ enum PtOpType {
 /// Memory Management Unit (MMU) state is properly managed and Translation
 /// Lookaside Buffer (TLB) entries are flushed.
 pub(crate) struct PtUpdateContext<'ctx, 'drm> {
-    /// Device used for DMA-mapping GEM shmem SG tables.
+    /// Device used for log messages.
     dev: &'ctx Device<Bound>,
+    /// DMA handle used to map GEM shmem SG tables.
+    dma: dma::Handle<'ctx>,
 
     /// Page table.
     pt: &'ctx IoPageTable<'drm, ARM64LPAES1>,
@@ -248,7 +251,7 @@ impl<'ctx, 'drm> PtUpdateContext<'ctx, 'drm> {
     /// The context will automatically flush the TLB and
     /// complete the update when dropped.
     fn new(
-        dev: &'ctx Device<Bound>,
+        dma: dma::Handle<'ctx>,
         pt: &'ctx IoPageTable<'drm, ARM64LPAES1>,
         mmu: &'ctx Mmu<'drm>,
         as_data: &'ctx VmAsData<'drm>,
@@ -259,7 +262,8 @@ fn new(
         mmu.start_vm_update(as_data, &region)?;
 
         Ok(Self {
-            dev,
+            dev: dma.device(),
+            dma,
             pt,
             mmu,
             as_data,
@@ -321,8 +325,10 @@ pub(crate) struct Vm<'drm> {
     as_data: Arc<VmAsData<'drm>>,
     /// MMU manager.
     mmu: Arc<Mmu<'drm>>,
-    /// Parent device used for DMA mapping and page-table operations.
+    /// Parent device.
     dev: &'drm Device<Bound>,
+    /// DMA handle used for mappings and page-table operations.
+    dma: dma::Handle<'drm>,
     /// DRM GPUVM core for managing virtual address space.
     #[pin]
     gpuvm_unique: Mutex<UniqueRefGpuVm<GpuVmData<'drm>>>,
@@ -339,11 +345,12 @@ impl<'drm> Vm<'drm> {
     /// The VM is initialized with a page table configured according to the GPU's
     /// address translation capabilities and registered with the GPUVM framework.
     pub(crate) fn new(
-        dev: &'drm Device<Bound>,
+        dma: dma::Handle<'drm>,
         ddev: &TyrDrmDevice,
         mmu: ArcBorrow<'_, Mmu<'drm>>,
         gpu_info: &GpuInfo,
     ) -> Result<Arc<Vm<'drm>>> {
+        let dev = dma.device();
         let mmu_features = MMU_FEATURES::from_raw(gpu_info.mmu_features);
         let va_bits = mmu_features.va_bits().get();
         let pa_bits = mmu_features.pa_bits().get();
@@ -371,12 +378,13 @@ pub(crate) fn new(
         })?;
         let gpuvm = ARef::from(&*gpuvm_unique);
 
-        let as_data = Arc::pin_init(VmAsData::new(&mmu, dev, va_bits, pa_bits), GFP_KERNEL)?;
+        let as_data = Arc::pin_init(VmAsData::new(&mmu, dma, va_bits, pa_bits), GFP_KERNEL)?;
 
         let vm = Arc::pin_init(
             pin_init!(Self{
                 as_data,
                 dev,
+                dma,
                 mmu: mmu.into(),
                 gpuvm,
                 gpuvm_unique <- new_mutex!(gpuvm_unique),
@@ -388,7 +396,7 @@ pub(crate) fn new(
         Ok(vm)
     }
 
-    /// Returns the parent device used by this VM for DMA mapping and page-table operations.
+    /// Returns the parent device.
     pub(crate) fn dev(&self) -> &'drm Device<Bound> {
         self.dev
     }
@@ -435,7 +443,7 @@ fn exec_op<'a>(
         match req.op_type {
             VmOpType::Map(args) => {
                 let mut pt_upd = PtUpdateContext::new(
-                    self.dev,
+                    self.dma,
                     pt,
                     &self.mmu,
                     &self.as_data,
@@ -457,7 +465,7 @@ fn exec_op<'a>(
             }
             VmOpType::Unmap => {
                 let mut pt_upd = PtUpdateContext::new(
-                    self.dev,
+                    self.dma,
                     pt,
                     &self.mmu,
                     &self.as_data,
@@ -630,7 +638,7 @@ fn sm_step_map<'op>(
             return Err(EINVAL);
         }
 
-        let sgt = op.obj().sg_table(context.dev).inspect_err(|e| {
+        let sgt = op.obj().sg_table(context.dma.device()).inspect_err(|e| {
             dev_err!(context.dev, "Failed to get sg_table: {:?}", e);
         })?;
         let prot = match &context.op_type {
-- 
2.51.2


^ permalink raw reply	[flat|nested] 11+ messages in thread

* [RFC PATCH v2 05/10] samples: rust: dma: configure DMA through dma::Setup
  2026-11-29 22:24 [RFC PATCH v2 00/10] rust: dma: require device configuration before DMA Matteo Kloiber
                   ` (3 preceding siblings ...)
  2026-11-29 22:24 ` [RFC PATCH v2 04/10] drm/tyr: " Matteo Kloiber
@ 2026-11-29 22:24 ` Matteo Kloiber
  2026-11-29 22:24 ` [RFC PATCH v2 06/10] rust: dma: require a Handle for coherent allocations Matteo Kloiber
                   ` (4 subsequent siblings)
  9 siblings, 0 replies; 11+ messages in thread
From: Matteo Kloiber @ 2026-11-29 22:24 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot, Alice Ryhl, Abdiel Janulgue,
	Robin Murphy, Andreas Hindborg, Gary Guo
  Cc: Daniel Almeida, Miguel Ojeda, David Airlie, Simona Vetter,
	Bjorn Helgaas, Krzysztof Wilczyński, Greg Kroah-Hartman,
	rust-for-linux, driver-core, dri-devel, nova-gpu, linux-kernel,
	Matteo Kloiber

Replace the unsafe dma::Device setter with dma::Setup::configure() and
use the returned dma::Handle for the coherent allocation and the SG
table. Both APIs still take a device, so hand them dma.device() for
now.

Set the maximum segment size to 64 KiB explicitly. This is the value
the PCI core sets for every device, and the sample relied on it
implicitly.

Signed-off-by: Matteo Kloiber <kernel@matt3o12.de>
---
 samples/rust/rust_dma.rs | 19 +++++++++++++------
 1 file changed, 13 insertions(+), 6 deletions(-)

diff --git a/samples/rust/rust_dma.rs b/samples/rust/rust_dma.rs
index b6a36d10bf74..c84107e5b2c3 100644
--- a/samples/rust/rust_dma.rs
+++ b/samples/rust/rust_dma.rs
@@ -4,15 +4,17 @@
 //!
 //! To make this driver probe, QEMU must be run with `-device pci-testdev`.
 
+use core::num::NonZeroU32;
+
 use kernel::{
     device::{
         Bound,
         Core, //
     },
     dma::{
+        self,
         Coherent,
         DataDirection,
-        Device,
         DmaMask, //
     },
     io::{
@@ -27,6 +29,7 @@
         Owned,
         SGTable, //
     }, //
+    sizes::SizeConstants,
 };
 
 struct DmaSampleDriver;
@@ -77,19 +80,23 @@ impl pci::Driver for DmaSampleDriver {
 
     fn probe<'bound>(
         pdev: &'bound pci::Device<Core<'_>>,
-        _tokens: pci::InitTokens<'bound>,
+        tokens: pci::InitTokens<'bound>,
         _info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
+        let pci::InitTokens { dma: setup, .. } = tokens;
         pin_init::pin_init_scope(move || {
             dev_info!(pdev, "Probe DMA test driver.\n");
 
             let mask = DmaMask::new::<64>();
 
-            // SAFETY: There are no concurrent calls to DMA allocation and mapping primitives.
-            unsafe { pdev.dma_set_mask_and_coherent(mask)? };
+            let dma = setup.configure(dma::Params {
+                streaming_mask: Some(mask),
+                coherent_mask: Some(mask),
+                max_seg_size: Some(const { NonZeroU32::new(u32::SZ_64K).unwrap() }),
+            })?;
 
             let ca: Coherent<'_, [MyStruct]> =
-                Coherent::zeroed_slice(pdev.as_ref(), TEST_VALUES.len(), GFP_KERNEL)?;
+                Coherent::zeroed_slice(dma.device(), TEST_VALUES.len(), GFP_KERNEL)?;
 
             for (i, value) in TEST_VALUES.into_iter().enumerate() {
                 io_project!(ca, [panic: i]).copy_write(MyStruct::new(value.0, value.1));
@@ -98,7 +105,7 @@ fn probe<'bound>(
             let size = 4 * page::PAGE_SIZE;
             let pages = VVec::with_capacity(size, GFP_KERNEL)?;
 
-            let sgt = SGTable::new(pdev.as_ref(), pages, DataDirection::ToDevice, GFP_KERNEL);
+            let sgt = SGTable::new(dma.device(), pages, DataDirection::ToDevice, GFP_KERNEL);
 
             Ok(try_pin_init!(Self::Data {
                 pdev,
-- 
2.51.2


^ permalink raw reply	[flat|nested] 11+ messages in thread

* [RFC PATCH v2 06/10] rust: dma: require a Handle for coherent allocations
  2026-11-29 22:24 [RFC PATCH v2 00/10] rust: dma: require device configuration before DMA Matteo Kloiber
                   ` (4 preceding siblings ...)
  2026-11-29 22:24 ` [RFC PATCH v2 05/10] samples: rust: dma: " Matteo Kloiber
@ 2026-11-29 22:24 ` Matteo Kloiber
  2026-11-29 22:24 ` [RFC PATCH v2 07/10] rust: scatterlist: require a dma::Handle for SGTable::new() Matteo Kloiber
                   ` (3 subsequent siblings)
  9 siblings, 0 replies; 11+ messages in thread
From: Matteo Kloiber @ 2026-11-29 22:24 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot, Alice Ryhl, Abdiel Janulgue,
	Robin Murphy, Andreas Hindborg, Gary Guo
  Cc: Daniel Almeida, Miguel Ojeda, David Airlie, Simona Vetter,
	Bjorn Helgaas, Krzysztof Wilczyński, Greg Kroah-Hartman,
	rust-for-linux, driver-core, dri-devel, nova-gpu, linux-kernel,
	Matteo Kloiber

Coherent, CoherentBox and CoherentHandle allocate for a plain bound
device, so nothing ties an allocation to a completed DMA configuration.

Make their constructors take a dma::Handle and store it in place of the
device reference. A handle only exists after Setup::configure(), so
coherent memory can no longer be allocated before the DMA parameters
are set.

Convert nova-core and the DMA sample. Both already hold a handle, so
they pass it directly instead of dma.device().

Signed-off-by: Matteo Kloiber <kernel@matt3o12.de>
---
 drivers/gpu/nova-core/falcon.rs               |   2 +-
 drivers/gpu/nova-core/fb.rs                   |   2 +-
 .../nova-core/firmware/fwsec/bootloader.rs    |   2 +-
 drivers/gpu/nova-core/firmware/gsp.rs         |   3 +-
 drivers/gpu/nova-core/firmware/gsp_fmc.rs     |   2 +-
 drivers/gpu/nova-core/firmware/radix3.rs      |   2 +-
 drivers/gpu/nova-core/firmware/riscv.rs       |   2 +-
 drivers/gpu/nova-core/fsp.rs                  |   2 +-
 drivers/gpu/nova-core/gsp.rs                  |   4 +-
 drivers/gpu/nova-core/gsp/cmdq.rs             |   2 +-
 drivers/gpu/nova-core/gsp/hal/gh100.rs        |   2 +-
 drivers/gpu/nova-core/gsp/hal/tu102.rs        |   2 +-
 drivers/gpu/nova-core/gsp/logbuffer.rs        |   2 +-
 rust/kernel/dma.rs                            | 161 ++++++++----------
 samples/rust/rust_dma.rs                      |   2 +-
 15 files changed, 85 insertions(+), 107 deletions(-)

diff --git a/drivers/gpu/nova-core/falcon.rs b/drivers/gpu/nova-core/falcon.rs
index c9ffda0208b0..9de2b5880630 100644
--- a/drivers/gpu/nova-core/falcon.rs
+++ b/drivers/gpu/nova-core/falcon.rs
@@ -649,7 +649,7 @@ fn dma_load<F: FalconFirmware<Target = E> + FalconDmaLoadable>(&self, fw: &F) ->
             // DMA copies are done in chunks of `MEM_BLOCK_ALIGNMENT`, so pad the length
             // accordingly and fill with `0`.
             let mut dma_obj = CoherentBox::zeroed_slice(
-                self.dma.device(),
+                self.dma,
                 fw_slice.len().next_multiple_of(MEM_BLOCK_ALIGNMENT),
                 GFP_KERNEL,
             )?;
diff --git a/drivers/gpu/nova-core/fb.rs b/drivers/gpu/nova-core/fb.rs
index a2505da09a79..164e14a8b6fc 100644
--- a/drivers/gpu/nova-core/fb.rs
+++ b/drivers/gpu/nova-core/fb.rs
@@ -62,7 +62,7 @@ pub(crate) fn register(
         bar: Bar0<'sys>,
         chipset: Chipset,
     ) -> Result<Self> {
-        let page = CoherentHandle::alloc(dma.device(), kernel::page::PAGE_SIZE, GFP_KERNEL)?;
+        let page = CoherentHandle::alloc(dma, kernel::page::PAGE_SIZE, GFP_KERNEL)?;
 
         hal::fb_hal(chipset).write_sysmem_flush_page(bar, page.dma_address())?;
 
diff --git a/drivers/gpu/nova-core/firmware/fwsec/bootloader.rs b/drivers/gpu/nova-core/firmware/fwsec/bootloader.rs
index 49651a404286..d504c33d789f 100644
--- a/drivers/gpu/nova-core/firmware/fwsec/bootloader.rs
+++ b/drivers/gpu/nova-core/firmware/fwsec/bootloader.rs
@@ -80,7 +80,7 @@ pub(crate) fn new(
 
             (
                 align_padding,
-                Coherent::from_slice(dma.device(), firmware_obj.as_slice(), GFP_KERNEL)?,
+                Coherent::from_slice(dma, firmware_obj.as_slice(), GFP_KERNEL)?,
             )
         };
 
diff --git a/drivers/gpu/nova-core/firmware/gsp.rs b/drivers/gpu/nova-core/firmware/gsp.rs
index e5fce91337a8..aafa6c583421 100644
--- a/drivers/gpu/nova-core/firmware/gsp.rs
+++ b/drivers/gpu/nova-core/firmware/gsp.rs
@@ -54,8 +54,7 @@ pub(crate) fn new(dma: dma::Handle<'a>, chipset: Chipset) -> impl PinInit<Self,
             let filename = CString::try_from_fmt(fmt!("nvidia/{chip_name}/gsp/{file}"))?;
             firmware::request_into_buf(&filename, dev, fw_vvec.as_mut_slice())?;
 
-            let signatures =
-                Coherent::from_slice(dma.device(), tlv.get_bytes(b"SIGN")?, GFP_KERNEL)?;
+            let signatures = Coherent::from_slice(dma, tlv.get_bytes(b"SIGN")?, GFP_KERNEL)?;
 
             Ok(try_pin_init!(Self {
                 radix3 <- Radix3::new(dma, fw_vvec),
diff --git a/drivers/gpu/nova-core/firmware/gsp_fmc.rs b/drivers/gpu/nova-core/firmware/gsp_fmc.rs
index 230d631beaf4..6c52eb2dbed9 100644
--- a/drivers/gpu/nova-core/firmware/gsp_fmc.rs
+++ b/drivers/gpu/nova-core/firmware/gsp_fmc.rs
@@ -62,7 +62,7 @@ pub(crate) fn new(dma: dma::Handle<'a>, chipset: Chipset) -> Result<Self> {
         );
 
         let fmc_image_data = tlv.get_bytes(b"BLOB")?;
-        let fmc_image = Coherent::from_slice(dma.device(), fmc_image_data, GFP_KERNEL)?;
+        let fmc_image = Coherent::from_slice(dma, fmc_image_data, GFP_KERNEL)?;
 
         Ok(Self {
             fmc_image,
diff --git a/drivers/gpu/nova-core/firmware/radix3.rs b/drivers/gpu/nova-core/firmware/radix3.rs
index 5e10263e8313..a00a583f7351 100644
--- a/drivers/gpu/nova-core/firmware/radix3.rs
+++ b/drivers/gpu/nova-core/firmware/radix3.rs
@@ -77,7 +77,7 @@ pub(crate) fn new(dma: dma::Handle<'a>, data: VVec<u8>) -> impl PinInit<Self, Er
                     // Create level 0 page table data and fill its first entry with the level 1
                     // table.
                     let mut level0 = CoherentBox::<'_, [u64]>::zeroed_slice(
-                        dma.device(),
+                        dma,
                         GSP_PAGE_SIZE / size_of::<u64>(),
                         GFP_KERNEL
                     )?;
diff --git a/drivers/gpu/nova-core/firmware/riscv.rs b/drivers/gpu/nova-core/firmware/riscv.rs
index ce0da2efe34e..f78af9bba740 100644
--- a/drivers/gpu/nova-core/firmware/riscv.rs
+++ b/drivers/gpu/nova-core/firmware/riscv.rs
@@ -44,7 +44,7 @@ pub(crate) fn new(dma: dma::Handle<'a>, fw: &Firmware) -> Result<Self> {
         let manifest_offset = tlv.get_u32(b"MFOF")?;
         let app_version = tlv.get_u32(b"APPV")?;
 
-        let ucode = Coherent::from_slice(dma.device(), tlv.get_bytes(b"BLOB")?, GFP_KERNEL)?;
+        let ucode = Coherent::from_slice(dma, tlv.get_bytes(b"BLOB")?, GFP_KERNEL)?;
 
         Ok(Self {
             ucode,
diff --git a/drivers/gpu/nova-core/fsp.rs b/drivers/gpu/nova-core/fsp.rs
index 17da2efbf0e0..9675d3941ed5 100644
--- a/drivers/gpu/nova-core/fsp.rs
+++ b/drivers/gpu/nova-core/fsp.rs
@@ -372,7 +372,7 @@ pub(crate) fn new(
 
         Ok(Self {
             chipset,
-            fmc_boot_params: Coherent::init(dma.device(), GFP_KERNEL, init)?,
+            fmc_boot_params: Coherent::init(dma, GFP_KERNEL, init)?,
             resume,
             _wpr_meta: wpr_meta,
             _libos: libos,
diff --git a/drivers/gpu/nova-core/gsp.rs b/drivers/gpu/nova-core/gsp.rs
index 908ecfbcd2aa..e218a1628646 100644
--- a/drivers/gpu/nova-core/gsp.rs
+++ b/drivers/gpu/nova-core/gsp.rs
@@ -126,10 +126,10 @@ pub(crate) fn new(dma: dma::Handle<'gsp>, bar: Bar0<'gsp>) -> impl PinInit<Self,
             // kgspSetupLibosInitArgs_IMPL (creates pLibosInitArgs[] array)
             Ok(try_pin_init!(Self {
                 cmdq <- Cmdq::new(dma, bar),
-                rmargs: Coherent::init(dma.device(), GFP_KERNEL, GspArgumentsPadded::new(&cmdq))?,
+                rmargs: Coherent::init(dma, GFP_KERNEL, GspArgumentsPadded::new(&cmdq))?,
                 libos: {
                     let mut libos = CoherentBox::zeroed_slice(
-                        dma.device(),
+                        dma,
                         GSP_PAGE_SIZE / size_of::<LibosMemoryRegionInitArgument>(),
                         GFP_KERNEL,
                     )?;
diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/cmdq.rs
index d34174998f3d..e442d956ce19 100644
--- a/drivers/gpu/nova-core/gsp/cmdq.rs
+++ b/drivers/gpu/nova-core/gsp/cmdq.rs
@@ -180,7 +180,7 @@ fn new(dma: dma::Handle<'a>, bar: Bar0<'a>) -> Result<Self> {
         const MSGQ_SIZE: u32 = cv!(size_of::<Msgq>());
         const RX_HDR_OFF: u32 = cv!(mem::offset_of!(Msgq, rx));
 
-        let mut gsp_mem = CoherentBox::<'_, GspMem>::zeroed(dma.device(), GFP_KERNEL)?;
+        let mut gsp_mem = CoherentBox::<'_, GspMem>::zeroed(dma, GFP_KERNEL)?;
         gsp_mem.cpuq.tx = MsgqTxHeader::new(MSGQ_SIZE, RX_HDR_OFF, MSGQ_NUM_PAGES);
         gsp_mem.cpuq.rx = MsgqRxHeader::new();
 
diff --git a/drivers/gpu/nova-core/gsp/hal/gh100.rs b/drivers/gpu/nova-core/gsp/hal/gh100.rs
index f194df6656aa..aad4a6b222aa 100644
--- a/drivers/gpu/nova-core/gsp/hal/gh100.rs
+++ b/drivers/gpu/nova-core/gsp/hal/gh100.rs
@@ -155,7 +155,7 @@ fn boot<'gpu>(
         dev_dbg!(dev, "{:#x?}\n", fb_sizes);
 
         let wpr_meta = Coherent::init(
-            ctx.dma.device(),
+            ctx.dma,
             GFP_KERNEL,
             GspFwWprMeta::from_sizes(gsp_fw, &fb_sizes),
         )?;
diff --git a/drivers/gpu/nova-core/gsp/hal/tu102.rs b/drivers/gpu/nova-core/gsp/hal/tu102.rs
index 44a758335118..ca92b0d66e51 100644
--- a/drivers/gpu/nova-core/gsp/hal/tu102.rs
+++ b/drivers/gpu/nova-core/gsp/hal/tu102.rs
@@ -272,7 +272,7 @@ fn boot<'gpu>(
         // Declared before the unload guard so that if Booter fails while running, SEC2 is reset
         // by the guard before this allocation is freed.
         let wpr_meta = Coherent::init(
-            dma.device(),
+            dma,
             GFP_KERNEL,
             GspFwWprMeta::from_ranges(gsp_fw, &fb_ranges),
         )?;
diff --git a/drivers/gpu/nova-core/gsp/logbuffer.rs b/drivers/gpu/nova-core/gsp/logbuffer.rs
index 57d063c15502..2b3494470a83 100644
--- a/drivers/gpu/nova-core/gsp/logbuffer.rs
+++ b/drivers/gpu/nova-core/gsp/logbuffer.rs
@@ -52,7 +52,7 @@
 impl<'a> LogBuffer<'a> {
     /// Creates a new `LogBuffer` mapped on the device.
     fn new(dma: dma::Handle<'a>) -> Result<Self> {
-        let obj = Self(Coherent::zeroed(dma.device(), GFP_KERNEL)?);
+        let obj = Self(Coherent::zeroed(dma, GFP_KERNEL)?);
 
         let start_addr = obj.0.dma_address();
 
diff --git a/rust/kernel/dma.rs b/rust/kernel/dma.rs
index 9c3cbce77ce9..456ae9f90602 100644
--- a/rust/kernel/dma.rs
+++ b/rust/kernel/dma.rs
@@ -69,7 +69,7 @@
 ///     max_seg_size: Some(NonZeroU32::MAX),
 /// })?;
 ///
-/// let _buf = Coherent::<u64>::zeroed(dma.device(), GFP_KERNEL)?;
+/// let _buf = Coherent::<u64>::zeroed(dma, GFP_KERNEL)?;
 /// # Ok::<(), Error>(()) }
 /// ```
 pub struct Params {
@@ -158,6 +158,12 @@ impl<'bound> Handle<'bound> {
     pub fn device(self) -> &'bound device::Device<Bound> {
         self.dev
     }
+
+    /// Returns the raw `struct device` pointer of the handle's device.
+    #[inline]
+    pub(crate) fn as_raw(self) -> *mut bindings::device {
+        self.dev.as_raw()
+    }
 }
 
 /// Trait to be implemented by DMA capable bus devices.
@@ -329,13 +335,12 @@ pub const fn value(&self) -> u64 {
 /// # Examples
 ///
 /// ```
-/// # use kernel::device::{Bound, Device};
 /// use kernel::dma::{attrs::*, Coherent};
 ///
-/// # fn test(dev: &Device<Bound>) -> Result {
+/// # fn test(dma: kernel::dma::Handle<'_>) -> Result {
 /// let attribs = DMA_ATTR_FORCE_CONTIGUOUS | DMA_ATTR_NO_WARN;
 /// let c: Coherent<'_, [u64]> =
-///     Coherent::zeroed_slice_with_attrs(dev, 4, GFP_KERNEL, attribs)?;
+///     Coherent::zeroed_slice_with_attrs(dma, 4, GFP_KERNEL, attribs)?;
 /// # Ok::<(), Error>(()) }
 /// ```
 #[derive(Clone, Copy, PartialEq)]
@@ -492,17 +497,13 @@ fn from(direction: DataDirection) -> Self {
 /// `CoherentBox<T>`:
 ///
 /// ```
-/// # use kernel::device::{
-/// #     Bound,
-/// #     Device,
-/// # };
 /// use kernel::dma::{attrs::*,
 ///     Coherent,
 ///     CoherentBox,
 /// };
 ///
-/// # fn test(dev: &Device<Bound>) -> Result {
-/// let mut dmem: CoherentBox<'_, u64> = CoherentBox::zeroed(dev, GFP_KERNEL)?;
+/// # fn test(dma: kernel::dma::Handle<'_>) -> Result {
+/// let mut dmem: CoherentBox<'_, u64> = CoherentBox::zeroed(dma, GFP_KERNEL)?;
 /// *dmem = 42;
 /// let dmem: Coherent<'_, u64> = dmem.into();
 /// # Ok::<(), Error>(()) }
@@ -512,17 +513,13 @@ fn from(direction: DataDirection) -> Self {
 ///
 ///
 /// ```
-/// # use kernel::device::{
-/// #     Bound,
-/// #     Device,
-/// # };
 /// use kernel::dma::{attrs::*,
 ///     Coherent,
 ///     CoherentBox,
 /// };
 ///
-/// # fn test(dev: &Device<Bound>) -> Result {
-/// let mut dmem: CoherentBox<'_, [u64]> = CoherentBox::zeroed_slice(dev, 4, GFP_KERNEL)?;
+/// # fn test(dma: kernel::dma::Handle<'_>) -> Result {
+/// let mut dmem: CoherentBox<'_, [u64]> = CoherentBox::zeroed_slice(dma, 4, GFP_KERNEL)?;
 /// dmem.fill(42);
 /// let dmem: Coherent<'_, [u64]> = dmem.into();
 /// # Ok::<(), Error>(()) }
@@ -533,22 +530,22 @@ impl<'a, T: AsBytes + FromBytes> CoherentBox<'a, [T]> {
     /// [`CoherentBox`] variant of [`Coherent::zeroed_slice_with_attrs`].
     #[inline]
     pub fn zeroed_slice_with_attrs(
-        dev: &'a device::Device<Bound>,
+        dma: Handle<'a>,
         count: usize,
         gfp_flags: kernel::alloc::Flags,
         dma_attrs: Attrs,
     ) -> Result<Self> {
-        Coherent::zeroed_slice_with_attrs(dev, count, gfp_flags, dma_attrs).map(Self)
+        Coherent::zeroed_slice_with_attrs(dma, count, gfp_flags, dma_attrs).map(Self)
     }
 
     /// Same as [CoherentBox::zeroed_slice_with_attrs], but with `dma::Attrs(0)`.
     #[inline]
     pub fn zeroed_slice(
-        dev: &'a device::Device<Bound>,
+        dma: Handle<'a>,
         count: usize,
         gfp_flags: kernel::alloc::Flags,
     ) -> Result<Self> {
-        Self::zeroed_slice_with_attrs(dev, count, gfp_flags, Attrs(0))
+        Self::zeroed_slice_with_attrs(dma, count, gfp_flags, Attrs(0))
     }
 
     /// Initializes the element at `i` using the given initializer.
@@ -584,22 +581,21 @@ pub fn init_at<E>(&mut self, i: usize, init: impl Init<T, E>) -> Result
     /// ```
     /// use core::ops::Deref;
     ///
-    /// # use kernel::device::{Bound, Device};
     /// use kernel::dma::{
     ///     attrs::*,
     ///     CoherentBox
     /// };
     ///
-    /// # fn test(dev: &Device<Bound>) -> Result {
+    /// # fn test(dma: kernel::dma::Handle<'_>) -> Result {
     /// let data = [0u8, 1u8, 2u8, 3u8];
     /// let c: CoherentBox<'_, [u8]> =
-    ///     CoherentBox::from_slice_with_attrs(dev, &data, GFP_KERNEL, DMA_ATTR_NO_WARN)?;
+    ///     CoherentBox::from_slice_with_attrs(dma, &data, GFP_KERNEL, DMA_ATTR_NO_WARN)?;
     ///
     /// assert_eq!(c.deref(), &data);
     /// # Ok::<(), Error>(()) }
     /// ```
     pub fn from_slice_with_attrs(
-        dev: &'a device::Device<Bound>,
+        dma: Handle<'a>,
         data: &[T],
         gfp_flags: kernel::alloc::Flags,
         dma_attrs: Attrs,
@@ -608,7 +604,7 @@ pub fn from_slice_with_attrs(
         T: Copy,
     {
         let mut slice = Self(Coherent::<T>::alloc_slice_with_attrs(
-            dev,
+            dma,
             data.len(),
             gfp_flags,
             dma_attrs,
@@ -623,15 +619,11 @@ pub fn from_slice_with_attrs(
     /// Performs the same functionality as [`CoherentBox::from_slice_with_attrs`], except the
     /// `dma_attrs` is 0 by default.
     #[inline]
-    pub fn from_slice(
-        dev: &'a device::Device<Bound>,
-        data: &[T],
-        gfp_flags: kernel::alloc::Flags,
-    ) -> Result<Self>
+    pub fn from_slice(dma: Handle<'a>, data: &[T], gfp_flags: kernel::alloc::Flags) -> Result<Self>
     where
         T: Copy,
     {
-        Self::from_slice_with_attrs(dev, data, gfp_flags, Attrs(0))
+        Self::from_slice_with_attrs(dma, data, gfp_flags, Attrs(0))
     }
 }
 
@@ -639,17 +631,17 @@ impl<'a, T: AsBytes + FromBytes> CoherentBox<'a, T> {
     /// Same as [`CoherentBox::zeroed_slice_with_attrs`], but for a single element.
     #[inline]
     pub fn zeroed_with_attrs(
-        dev: &'a device::Device<Bound>,
+        dma: Handle<'a>,
         gfp_flags: kernel::alloc::Flags,
         dma_attrs: Attrs,
     ) -> Result<Self> {
-        Coherent::zeroed_with_attrs(dev, gfp_flags, dma_attrs).map(Self)
+        Coherent::zeroed_with_attrs(dma, gfp_flags, dma_attrs).map(Self)
     }
 
     /// Same as [`CoherentBox::zeroed_slice`], but for a single element.
     #[inline]
-    pub fn zeroed(dev: &'a device::Device<Bound>, gfp_flags: kernel::alloc::Flags) -> Result<Self> {
-        Self::zeroed_with_attrs(dev, gfp_flags, Attrs(0))
+    pub fn zeroed(dma: Handle<'a>, gfp_flags: kernel::alloc::Flags) -> Result<Self> {
+        Self::zeroed_with_attrs(dma, gfp_flags, Attrs(0))
     }
 }
 
@@ -707,7 +699,7 @@ fn from(value: CoherentBox<'a, T>) -> Self {
 // constructors `unsafe` to prevent this is considered too restrictive for the common case; this
 // soundness hole is accepted for now.
 pub struct Coherent<'a, T: KnownSize + ?Sized> {
-    dev: &'a device::Device<Bound>,
+    dma: Handle<'a>,
     dma_addr: DmaAddress,
     cpu_addr: NonNull<T>,
     dma_attrs: Attrs,
@@ -772,7 +764,7 @@ pub unsafe fn as_mut(&self) -> &mut T {
 impl<'a, T: AsBytes + FromBytes> Coherent<'a, T> {
     /// Allocates a region of `T` of coherent memory.
     fn alloc_with_attrs(
-        dev: &'a device::Device<Bound>,
+        dma: Handle<'a>,
         gfp_flags: kernel::alloc::Flags,
         dma_attrs: Attrs,
     ) -> Result<Self> {
@@ -784,10 +776,10 @@ fn alloc_with_attrs(
         }
 
         let mut dma_addr = 0;
-        // SAFETY: Device pointer is guaranteed as valid by the type invariant on `Device`.
+        // SAFETY: Device pointer is guaranteed as valid by the type invariant on `device::Device`.
         let addr = unsafe {
             bindings::dma_alloc_attrs(
-                dev.as_raw(),
+                dma.as_raw(),
                 core::mem::size_of::<T>(),
                 &mut dma_addr,
                 gfp_flags.as_raw(),
@@ -798,9 +790,9 @@ fn alloc_with_attrs(
         // INVARIANT:
         // - We just successfully allocated a coherent region which is adequately sized for `T`,
         //   hence the cpu address is valid.
-        // - `dev` is a valid reference to a bound device that outlives this allocation.
+        // - `dma` is a configured DMA handle for a device that outlives this allocation.
         Ok(Self {
-            dev,
+            dma,
             dma_addr,
             cpu_addr,
             dma_attrs,
@@ -812,40 +804,36 @@ fn alloc_with_attrs(
     /// # Examples
     ///
     /// ```
-    /// # use kernel::device::{
-    /// #     Bound,
-    /// #     Device,
-    /// # };
     /// use kernel::dma::{
     ///     attrs::*,
     ///     Coherent,
     /// };
     ///
-    /// # fn test(dev: &Device<Bound>) -> Result {
+    /// # fn test(dma: kernel::dma::Handle<'_>) -> Result {
     /// let c: Coherent<'_, [u64; 4]> =
-    ///     Coherent::zeroed_with_attrs(dev, GFP_KERNEL, DMA_ATTR_NO_WARN)?;
+    ///     Coherent::zeroed_with_attrs(dma, GFP_KERNEL, DMA_ATTR_NO_WARN)?;
     /// # Ok::<(), Error>(()) }
     /// ```
     #[inline]
     pub fn zeroed_with_attrs(
-        dev: &'a device::Device<Bound>,
+        dma: Handle<'a>,
         gfp_flags: kernel::alloc::Flags,
         dma_attrs: Attrs,
     ) -> Result<Self> {
-        Self::alloc_with_attrs(dev, gfp_flags | __GFP_ZERO, dma_attrs)
+        Self::alloc_with_attrs(dma, gfp_flags | __GFP_ZERO, dma_attrs)
     }
 
     /// Performs the same functionality as [`Coherent::zeroed_with_attrs`], except the
     /// `dma_attrs` is 0 by default.
     #[inline]
-    pub fn zeroed(dev: &'a device::Device<Bound>, gfp_flags: kernel::alloc::Flags) -> Result<Self> {
-        Self::zeroed_with_attrs(dev, gfp_flags, Attrs(0))
+    pub fn zeroed(dma: Handle<'a>, gfp_flags: kernel::alloc::Flags) -> Result<Self> {
+        Self::zeroed_with_attrs(dma, gfp_flags, Attrs(0))
     }
 
     /// Same as [`Coherent::zeroed_with_attrs`], but instead of a zero-initialization the memory is
     /// initialized with `init`.
     pub fn init_with_attrs<E>(
-        dev: &'a device::Device<Bound>,
+        dma: Handle<'a>,
         gfp_flags: kernel::alloc::Flags,
         dma_attrs: Attrs,
         init: impl Init<T, E>,
@@ -853,7 +841,7 @@ pub fn init_with_attrs<E>(
     where
         Error: From<E>,
     {
-        let dmem = Self::alloc_with_attrs(dev, gfp_flags, dma_attrs)?;
+        let dmem = Self::alloc_with_attrs(dma, gfp_flags, dma_attrs)?;
         let ptr = dmem.as_mut_ptr();
 
         // SAFETY:
@@ -870,19 +858,19 @@ pub fn init_with_attrs<E>(
     /// with `init`.
     #[inline]
     pub fn init<E>(
-        dev: &'a device::Device<Bound>,
+        dma: Handle<'a>,
         gfp_flags: kernel::alloc::Flags,
         init: impl Init<T, E>,
     ) -> Result<Self>
     where
         Error: From<E>,
     {
-        Self::init_with_attrs(dev, gfp_flags, Attrs(0), init)
+        Self::init_with_attrs(dma, gfp_flags, Attrs(0), init)
     }
 
     /// Allocates a region of `[T; len]` of coherent memory.
     fn alloc_slice_with_attrs(
-        dev: &'a device::Device<Bound>,
+        dma: Handle<'a>,
         len: usize,
         gfp_flags: kernel::alloc::Flags,
         dma_attrs: Attrs,
@@ -901,10 +889,10 @@ fn alloc_slice_with_attrs(
 
         let size = core::mem::size_of::<T>().checked_mul(len).ok_or(ENOMEM)?;
         let mut dma_addr = 0;
-        // SAFETY: Device pointer is guaranteed as valid by the type invariant on `Device`.
+        // SAFETY: Device pointer is guaranteed as valid by the type invariant on `device::Device`.
         let addr = unsafe {
             bindings::dma_alloc_attrs(
-                dev.as_raw(),
+                dma.as_raw(),
                 size,
                 &mut dma_addr,
                 gfp_flags.as_raw(),
@@ -915,9 +903,9 @@ fn alloc_slice_with_attrs(
         // INVARIANT:
         // - We just successfully allocated a coherent region which is adequately sized for
         //   `[T; len]`, hence the cpu address is valid.
-        // - `dev` is a valid reference to a bound device that outlives this allocation.
+        // - `dma` is a configured DMA handle for a device that outlives this allocation.
         Ok(Coherent {
-            dev,
+            dma,
             dma_addr,
             cpu_addr,
             dma_attrs,
@@ -932,39 +920,35 @@ fn alloc_slice_with_attrs(
     /// # Examples
     ///
     /// ```
-    /// # use kernel::device::{
-    /// #     Bound,
-    /// #     Device,
-    /// # };
     /// use kernel::dma::{
     ///     attrs::*,
     ///     Coherent,
     /// };
     ///
-    /// # fn test(dev: &Device<Bound>) -> Result {
+    /// # fn test(dma: kernel::dma::Handle<'_>) -> Result {
     /// let c: Coherent<'_, [u64]> =
-    ///     Coherent::zeroed_slice_with_attrs(dev, 4, GFP_KERNEL, DMA_ATTR_NO_WARN)?;
+    ///     Coherent::zeroed_slice_with_attrs(dma, 4, GFP_KERNEL, DMA_ATTR_NO_WARN)?;
     /// # Ok::<(), Error>(()) }
     /// ```
     #[inline]
     pub fn zeroed_slice_with_attrs(
-        dev: &'a device::Device<Bound>,
+        dma: Handle<'a>,
         len: usize,
         gfp_flags: kernel::alloc::Flags,
         dma_attrs: Attrs,
     ) -> Result<Coherent<'a, [T]>> {
-        Coherent::alloc_slice_with_attrs(dev, len, gfp_flags | __GFP_ZERO, dma_attrs)
+        Coherent::alloc_slice_with_attrs(dma, len, gfp_flags | __GFP_ZERO, dma_attrs)
     }
 
     /// Performs the same functionality as [`Coherent::zeroed_slice_with_attrs`], except the
     /// `dma_attrs` is 0 by default.
     #[inline]
     pub fn zeroed_slice(
-        dev: &'a device::Device<Bound>,
+        dma: Handle<'a>,
         len: usize,
         gfp_flags: kernel::alloc::Flags,
     ) -> Result<Coherent<'a, [T]>> {
-        Self::zeroed_slice_with_attrs(dev, len, gfp_flags, Attrs(0))
+        Self::zeroed_slice_with_attrs(dma, len, gfp_flags, Attrs(0))
     }
 
     /// Allocates a region of coherent memory of the same size as `data` and initializes it with a
@@ -973,23 +957,22 @@ pub fn zeroed_slice(
     /// # Examples
     ///
     /// ```
-    /// # use kernel::device::{Bound, Device};
     /// use kernel::dma::{
     ///     attrs::*,
     ///     Coherent
     /// };
     ///
-    /// # fn test(dev: &Device<Bound>) -> Result {
+    /// # fn test(dma: kernel::dma::Handle<'_>) -> Result {
     /// let data = [0u8, 1u8, 2u8, 3u8];
     /// // `c` has the same content as `data`.
     /// let c: Coherent<'_, [u8]> =
-    ///     Coherent::from_slice_with_attrs(dev, &data, GFP_KERNEL, DMA_ATTR_NO_WARN)?;
+    ///     Coherent::from_slice_with_attrs(dma, &data, GFP_KERNEL, DMA_ATTR_NO_WARN)?;
     ///
     /// # Ok::<(), Error>(()) }
     /// ```
     #[inline]
     pub fn from_slice_with_attrs(
-        dev: &'a device::Device<Bound>,
+        dma: Handle<'a>,
         data: &[T],
         gfp_flags: kernel::alloc::Flags,
         dma_attrs: Attrs,
@@ -997,21 +980,21 @@ pub fn from_slice_with_attrs(
     where
         T: Copy,
     {
-        CoherentBox::from_slice_with_attrs(dev, data, gfp_flags, dma_attrs).map(Into::into)
+        CoherentBox::from_slice_with_attrs(dma, data, gfp_flags, dma_attrs).map(Into::into)
     }
 
     /// Performs the same functionality as [`Coherent::from_slice_with_attrs`], except the
     /// `dma_attrs` is 0 by default.
     #[inline]
     pub fn from_slice(
-        dev: &'a device::Device<Bound>,
+        dma: Handle<'a>,
         data: &[T],
         gfp_flags: kernel::alloc::Flags,
     ) -> Result<Coherent<'a, [T]>>
     where
         T: Copy,
     {
-        Self::from_slice_with_attrs(dev, data, gfp_flags, Attrs(0))
+        Self::from_slice_with_attrs(dma, data, gfp_flags, Attrs(0))
     }
 }
 
@@ -1036,7 +1019,7 @@ fn drop(&mut self) {
         // `Coherent`.
         unsafe {
             bindings::dma_free_attrs(
-                self.dev.as_raw(),
+                self.dma.as_raw(),
                 size,
                 self.cpu_addr.as_ptr().cast(),
                 self.dma_addr,
@@ -1103,7 +1086,7 @@ fn write_to_slice(
 /// - `dma_attrs` contains the attributes used for the allocation, always including
 ///   `DMA_ATTR_NO_KERNEL_MAPPING`.
 pub struct CoherentHandle<'a> {
-    dev: &'a device::Device<Bound>,
+    dma: Handle<'a>,
     dma_addr: DmaAddress,
     cpu_handle: NonNull<c_void>,
     size: usize,
@@ -1118,7 +1101,7 @@ impl<'a> CoherentHandle<'a> {
     ///
     /// Returns `EINVAL` if `size` is zero, `ENOMEM` if the allocation fails.
     pub fn alloc_with_attrs(
-        dev: &'a device::Device<Bound>,
+        dma: Handle<'a>,
         size: usize,
         gfp_flags: kernel::alloc::Flags,
         dma_attrs: Attrs,
@@ -1129,10 +1112,10 @@ pub fn alloc_with_attrs(
 
         let dma_attrs = dma_attrs | Attrs(bindings::DMA_ATTR_NO_KERNEL_MAPPING);
         let mut dma_addr = 0;
-        // SAFETY: `dev.as_raw()` is valid by the type invariant on `device::Device`.
+        // SAFETY: `dma.as_raw()` is valid by the type invariant on `device::Device`.
         let cpu_handle = unsafe {
             bindings::dma_alloc_attrs(
-                dev.as_raw(),
+                dma.as_raw(),
                 size,
                 &mut dma_addr,
                 gfp_flags.as_raw(),
@@ -1144,9 +1127,9 @@ pub fn alloc_with_attrs(
 
         // INVARIANT: `cpu_handle` is the opaque handle from a successful `dma_alloc_attrs` call
         // with `DMA_ATTR_NO_KERNEL_MAPPING`, `dma_addr` is the corresponding DMA address,
-        // and `dev` is a valid reference to a bound device that outlives this allocation.
+        // and `dma` is a configured DMA handle for a device that outlives this allocation.
         Ok(Self {
-            dev,
+            dma,
             dma_addr,
             cpu_handle,
             size,
@@ -1156,12 +1139,8 @@ pub fn alloc_with_attrs(
 
     /// Allocates `size` bytes of coherent DMA memory without creating a kernel virtual mapping.
     #[inline]
-    pub fn alloc(
-        dev: &'a device::Device<Bound>,
-        size: usize,
-        gfp_flags: kernel::alloc::Flags,
-    ) -> Result<Self> {
-        Self::alloc_with_attrs(dev, size, gfp_flags, Attrs(0))
+    pub fn alloc(dma: Handle<'a>, size: usize, gfp_flags: kernel::alloc::Flags) -> Result<Self> {
+        Self::alloc_with_attrs(dma, size, gfp_flags, Attrs(0))
     }
 
     /// Returns the DMA address for this allocation.
@@ -1185,7 +1164,7 @@ fn drop(&mut self) {
         // `cpu_handle` is the opaque handle from `dma_alloc_attrs` and is passed back unchanged.
         unsafe {
             bindings::dma_free_attrs(
-                self.dev.as_raw(),
+                self.dma.as_raw(),
                 self.size,
                 self.cpu_handle.as_ptr(),
                 self.dma_addr,
diff --git a/samples/rust/rust_dma.rs b/samples/rust/rust_dma.rs
index c84107e5b2c3..1233aac8fe23 100644
--- a/samples/rust/rust_dma.rs
+++ b/samples/rust/rust_dma.rs
@@ -96,7 +96,7 @@ fn probe<'bound>(
             })?;
 
             let ca: Coherent<'_, [MyStruct]> =
-                Coherent::zeroed_slice(dma.device(), TEST_VALUES.len(), GFP_KERNEL)?;
+                Coherent::zeroed_slice(dma, TEST_VALUES.len(), GFP_KERNEL)?;
 
             for (i, value) in TEST_VALUES.into_iter().enumerate() {
                 io_project!(ca, [panic: i]).copy_write(MyStruct::new(value.0, value.1));
-- 
2.51.2


^ permalink raw reply	[flat|nested] 11+ messages in thread

* [RFC PATCH v2 07/10] rust: scatterlist: require a dma::Handle for SGTable::new()
  2026-11-29 22:24 [RFC PATCH v2 00/10] rust: dma: require device configuration before DMA Matteo Kloiber
                   ` (5 preceding siblings ...)
  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 ` Matteo Kloiber
  2026-11-29 22:24 ` [RFC PATCH v2 08/10] rust: iommu: require a dma::Handle for IoPageTable::new() Matteo Kloiber
                   ` (2 subsequent siblings)
  9 siblings, 0 replies; 11+ messages in thread
From: Matteo Kloiber @ 2026-11-29 22:24 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot, Alice Ryhl, Abdiel Janulgue,
	Robin Murphy, Andreas Hindborg, Gary Guo
  Cc: Daniel Almeida, Miguel Ojeda, David Airlie, Simona Vetter,
	Bjorn Helgaas, Krzysztof Wilczyński, Greg Kroah-Hartman,
	rust-for-linux, driver-core, dri-devel, nova-gpu, linux-kernel,
	Matteo Kloiber

SGTable::new() maps pages for a plain bound device. The mapping depends
on the device's DMA mask and maximum segment size, so it must not be
created before they are set.

Take a dma::Handle instead of the device. Convert nova-core and the DMA
sample, which already hold one.

Signed-off-by: Matteo Kloiber <kernel@matt3o12.de>
---
 drivers/gpu/nova-core/firmware/radix3.rs |  7 +++----
 rust/kernel/scatterlist.rs               | 22 +++++++++++-----------
 samples/rust/rust_dma.rs                 |  2 +-
 3 files changed, 15 insertions(+), 16 deletions(-)

diff --git a/drivers/gpu/nova-core/firmware/radix3.rs b/drivers/gpu/nova-core/firmware/radix3.rs
index a00a583f7351..1dfe6b96ab45 100644
--- a/drivers/gpu/nova-core/firmware/radix3.rs
+++ b/drivers/gpu/nova-core/firmware/radix3.rs
@@ -52,19 +52,18 @@ pub(crate) struct Radix3<'a> {
 impl<'a> Radix3<'a> {
     /// Builds a radix3 page table over `data`, mapped for the device to read. May sleep.
     pub(crate) fn new(dma: dma::Handle<'a>, data: VVec<u8>) -> impl PinInit<Self, Error> + 'a {
-        let dev = dma.device();
         let size = data.len();
 
         pin_init::pin_init_scope(move || {
             Ok(try_pin_init!(Self {
-                data <- SGTable::new(dev, data, DataDirection::ToDevice, GFP_KERNEL),
+                data <- SGTable::new(dma, data, DataDirection::ToDevice, GFP_KERNEL),
                 level2 <- {
                     build_lvl(&data)
-                        .map(|l2| SGTable::new(dev, l2, DataDirection::ToDevice, GFP_KERNEL))?
+                        .map(|l2| SGTable::new(dma, l2, DataDirection::ToDevice, GFP_KERNEL))?
                 },
                 level1 <- {
                     build_lvl(&level2)
-                        .map(|l1| SGTable::new(dev, l1, DataDirection::ToDevice, GFP_KERNEL))?
+                        .map(|l1| SGTable::new(dma, l1, DataDirection::ToDevice, GFP_KERNEL))?
                 },
                 level0: {
                     // Allocate the level 0 page table as a device-visible DMA object, and map the
diff --git a/rust/kernel/scatterlist.rs b/rust/kernel/scatterlist.rs
index 3a5250f85000..9a9deb7ace2e 100644
--- a/rust/kernel/scatterlist.rs
+++ b/rust/kernel/scatterlist.rs
@@ -333,12 +333,13 @@ impl<P> Owned<P>
 where
     for<'a> P: page::AsPageIter<Iter<'a> = VmallocPageIter<'a>> + 'static,
 {
-    fn new(
-        dev: &Device<Bound>,
+    fn new<'a>(
+        dma: dma::Handle<'a>,
         mut pages: P,
         dir: dma::DataDirection,
         flags: alloc::Flags,
-    ) -> Result<impl PinInit<Self, Error> + '_> {
+    ) -> Result<impl PinInit<Self, Error> + 'a> {
+        let dev = dma.device();
         let page_iter = pages.page_iter();
         let size = page_iter.size();
 
@@ -406,7 +407,7 @@ impl<P> SGTable<Owned<P>>
     ///
     /// # Parameters
     ///
-    /// * `dev`: The [`Device`] that will be performing the DMA.
+    /// * `dma`: A handle for the device whose DMA parameters have been configured.
     /// * `pages`: The entity providing the backing pages. It must implement [`page::AsPageIter`].
     ///   The ownership of this entity is moved into the new [`SGTable<Owned>`].
     /// * `dir`: The [`dma::DataDirection`] of the DMA transfer.
@@ -416,18 +417,17 @@ impl<P> SGTable<Owned<P>>
     ///
     /// ```
     /// use kernel::{
-    ///     device::{Bound, Device},
     ///     dma, page,
     ///     prelude::*,
     ///     scatterlist::{SGTable, Owned},
     /// };
     ///
-    /// fn test(dev: &Device<Bound>) -> Result {
+    /// fn test(dma: dma::Handle<'_>) -> Result {
     ///     let size = 4 * page::PAGE_SIZE;
     ///     let pages = VVec::<u8>::with_capacity(size, GFP_KERNEL)?;
     ///
     ///     let sgt = KBox::pin_init(SGTable::new(
-    ///         dev,
+    ///         dma,
     ///         pages,
     ///         dma::DataDirection::ToDevice,
     ///         GFP_KERNEL,
@@ -436,14 +436,14 @@ impl<P> SGTable<Owned<P>>
     ///     Ok(())
     /// }
     /// ```
-    pub fn new(
-        dev: &Device<Bound>,
+    pub fn new<'a>(
+        dma: dma::Handle<'a>,
         pages: P,
         dir: dma::DataDirection,
         flags: alloc::Flags,
-    ) -> impl PinInit<Self, Error> + '_ {
+    ) -> impl PinInit<Self, Error> + 'a {
         try_pin_init!(Self {
-            inner <- Owned::new(dev, pages, dir, flags)?
+            inner <- Owned::new(dma, pages, dir, flags)?
         })
     }
 }
diff --git a/samples/rust/rust_dma.rs b/samples/rust/rust_dma.rs
index 1233aac8fe23..8fb5b90d7aaa 100644
--- a/samples/rust/rust_dma.rs
+++ b/samples/rust/rust_dma.rs
@@ -105,7 +105,7 @@ fn probe<'bound>(
             let size = 4 * page::PAGE_SIZE;
             let pages = VVec::with_capacity(size, GFP_KERNEL)?;
 
-            let sgt = SGTable::new(dma.device(), pages, DataDirection::ToDevice, GFP_KERNEL);
+            let sgt = SGTable::new(dma, pages, DataDirection::ToDevice, GFP_KERNEL);
 
             Ok(try_pin_init!(Self::Data {
                 pdev,
-- 
2.51.2


^ permalink raw reply	[flat|nested] 11+ messages in thread

* [RFC PATCH v2 08/10] rust: iommu: require a dma::Handle for IoPageTable::new()
  2026-11-29 22:24 [RFC PATCH v2 00/10] rust: dma: require device configuration before DMA Matteo Kloiber
                   ` (6 preceding siblings ...)
  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 ` 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
  9 siblings, 0 replies; 11+ messages in thread
From: Matteo Kloiber @ 2026-11-29 22:24 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot, Alice Ryhl, Abdiel Janulgue,
	Robin Murphy, Andreas Hindborg, Gary Guo
  Cc: Daniel Almeida, Miguel Ojeda, David Airlie, Simona Vetter,
	Bjorn Helgaas, Krzysztof Wilczyński, Greg Kroah-Hartman,
	rust-for-linux, driver-core, dri-devel, nova-gpu, linux-kernel,
	Matteo Kloiber

The io-pgtable code DMA-maps its table pages for the device when the
tables are not walked coherently, which depends on the device's DMA
parameters.

Take a dma::Handle instead of the device in IoPageTable::new(), and
record in the type invariant that the device has been configured.
Convert Tyr, the only user.

Signed-off-by: Matteo Kloiber <kernel@matt3o12.de>
---
 drivers/gpu/drm/tyr/mmu/address_space.rs |  2 +-
 rust/kernel/iommu/pgtable.rs             | 24 +++++++++++++-----------
 2 files changed, 14 insertions(+), 12 deletions(-)

diff --git a/drivers/gpu/drm/tyr/mmu/address_space.rs b/drivers/gpu/drm/tyr/mmu/address_space.rs
index de7dce8e9ee6..ed131b8a6b57 100644
--- a/drivers/gpu/drm/tyr/mmu/address_space.rs
+++ b/drivers/gpu/drm/tyr/mmu/address_space.rs
@@ -102,7 +102,7 @@ pub(crate) fn new<'a>(
             coherent_walk: false,
         };
 
-        let page_table_init = IoPageTable::new(dma.device(), pt_config);
+        let page_table_init = IoPageTable::new(dma, pt_config);
 
         try_pin_init!(Self {
             as_seat: LockedBy::new(&mmu.as_manager, Seat::NoSeat),
diff --git a/rust/kernel/iommu/pgtable.rs b/rust/kernel/iommu/pgtable.rs
index 5f9b42ca92c2..78acef800011 100644
--- a/rust/kernel/iommu/pgtable.rs
+++ b/rust/kernel/iommu/pgtable.rs
@@ -12,10 +12,7 @@
 use crate::{
     alloc,
     bindings,
-    device::{
-        Bound,
-        Device, //
-    },
+    dma,
     error::to_result,
     io::PhysAddr,
     prelude::*, //
@@ -57,10 +54,11 @@ pub struct Config {
 ///
 /// # Invariants
 ///
-/// The pointer references a valid io page table.
+/// The pointer references a valid io page table whose device's DMA parameters have been
+/// configured and remain unchanged for the lifetime of the page table.
 pub struct IoPageTable<'a, F: IoPageTableFmt> {
     ptr: NonNull<bindings::io_pgtable_ops>,
-    _dev: PhantomData<&'a Device<Bound>>,
+    _dma: PhantomData<dma::Handle<'a>>,
     _marker: PhantomData<F>,
 }
 
@@ -77,8 +75,10 @@ pub trait IoPageTableFmt: 'static {
 
 impl<'a, F: IoPageTableFmt> IoPageTable<'a, F> {
     /// Create a new `IoPageTable`.
+    ///
+    /// Requires a configured DMA handle because non-coherent page tables may use DMA mappings.
     #[inline]
-    pub fn new(dev: &'a Device<Bound>, config: Config) -> Result<IoPageTable<'a, F>> {
+    pub fn new(dma: dma::Handle<'a>, config: Config) -> Result<IoPageTable<'a, F>> {
         let mut raw_cfg = bindings::io_pgtable_cfg {
             quirks: config.quirks,
             pgsize_bitmap: config.pgsize_bitmap,
@@ -86,7 +86,7 @@ pub fn new(dev: &'a Device<Bound>, config: Config) -> Result<IoPageTable<'a, F>>
             oas: config.oas,
             coherent_walk: config.coherent_walk,
             tlb: &raw const NOOP_FLUSH_OPS,
-            iommu_dev: dev.as_raw(),
+            iommu_dev: dma.as_raw(),
             ..Zeroable::zeroed()
         };
 
@@ -94,15 +94,17 @@ pub fn new(dev: &'a Device<Bound>, config: Config) -> Result<IoPageTable<'a, F>>
         // * The raw_cfg pointer is valid for the duration of this call.
         // * The provided `FLUSH_OPS` contains valid function pointers that accept a null pointer
         //   as cookie.
-        // * The caller ensures that the io pgtable does not outlive the device.
+        // * The DMA handle ensures that the device is configured and remains bound for `'a`.
+        //   The returned page table cannot outlive this lifetime.
         let ops = unsafe {
             bindings::alloc_io_pgtable_ops(F::FORMAT, &mut raw_cfg, core::ptr::null_mut())
         };
 
-        // INVARIANT: We successfully created a valid page table.
+        // INVARIANT: We successfully created a valid page table. The DMA handle guarantees
+        // that its device's parameters are configured and remain unchanged for `'a`.
         Ok(IoPageTable {
             ptr: NonNull::new(ops).ok_or(ENOMEM)?,
-            _dev: PhantomData,
+            _dma: PhantomData,
             _marker: PhantomData,
         })
     }
-- 
2.51.2


^ permalink raw reply	[flat|nested] 11+ messages in thread

* [RFC PATCH v2 09/10] rust: drm: require a dma::Handle for shmem sg_table()
  2026-11-29 22:24 [RFC PATCH v2 00/10] rust: dma: require device configuration before DMA Matteo Kloiber
                   ` (7 preceding siblings ...)
  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 ` Matteo Kloiber
  2026-11-29 22:24 ` [RFC PATCH v2 10/10] rust: dma: remove the Device trait and its setters Matteo Kloiber
  9 siblings, 0 replies; 11+ messages in thread
From: Matteo Kloiber @ 2026-11-29 22:24 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot, Alice Ryhl, Abdiel Janulgue,
	Robin Murphy, Andreas Hindborg, Gary Guo
  Cc: Daniel Almeida, Miguel Ojeda, David Airlie, Simona Vetter,
	Bjorn Helgaas, Krzysztof Wilczyński, Greg Kroah-Hartman,
	rust-for-linux, driver-core, dri-devel, nova-gpu, linux-kernel,
	Matteo Kloiber

shmem::Object::sg_table() DMA-maps the object's pages for the device
passed in. Take a dma::Handle instead, so the mapping cannot be created
before DMA is configured. Convert Tyr, the only user.

Add Handle::new_for_test(), so that the KUnit test can build a handle
for a faux device, which is never probed and so never gets a
dma::Setup.

DRM C callbacks that allocate or map DMA memory on the driver's behalf
do not go through the handle and are not covered by this change.

Signed-off-by: Matteo Kloiber <kernel@matt3o12.de>
---
 drivers/gpu/drm/tyr/vm.rs    |  2 +-
 rust/kernel/dma.rs           | 12 ++++++++++++
 rust/kernel/drm/gem/shmem.rs | 23 +++++++++--------------
 3 files changed, 22 insertions(+), 15 deletions(-)

diff --git a/drivers/gpu/drm/tyr/vm.rs b/drivers/gpu/drm/tyr/vm.rs
index 8465d065dceb..d3614ca602cc 100644
--- a/drivers/gpu/drm/tyr/vm.rs
+++ b/drivers/gpu/drm/tyr/vm.rs
@@ -638,7 +638,7 @@ fn sm_step_map<'op>(
             return Err(EINVAL);
         }
 
-        let sgt = op.obj().sg_table(context.dma.device()).inspect_err(|e| {
+        let sgt = op.obj().sg_table(context.dma).inspect_err(|e| {
             dev_err!(context.dev, "Failed to get sg_table: {:?}", e);
         })?;
         let prot = match &context.op_type {
diff --git a/rust/kernel/dma.rs b/rust/kernel/dma.rs
index 456ae9f90602..226d00397f56 100644
--- a/rust/kernel/dma.rs
+++ b/rust/kernel/dma.rs
@@ -164,6 +164,18 @@ pub fn device(self) -> &'bound device::Device<Bound> {
     pub(crate) fn as_raw(self) -> *mut bindings::device {
         self.dev.as_raw()
     }
+
+    /// Creates a handle for `dev` without calling [`Setup::configure`].
+    ///
+    /// For tests only.
+    #[cfg(CONFIG_KUNIT = "y")]
+    #[allow(dead_code)] // Only used by tests of other, optional abstractions.
+    #[inline]
+    pub(crate) fn new_for_test(dev: &'bound device::Device<Bound>) -> Self {
+        // INVARIANT: No DMA parameters were requested for `dev`, and tests do not change them while
+        // the handle exists.
+        Self { dev }
+    }
 }
 
 /// Trait to be implemented by DMA capable bus devices.
diff --git a/rust/kernel/drm/gem/shmem.rs b/rust/kernel/drm/gem/shmem.rs
index 2a07990ef366..f360e5bce0fc 100644
--- a/rust/kernel/drm/gem/shmem.rs
+++ b/rust/kernel/drm/gem/shmem.rs
@@ -11,11 +11,8 @@
 
 use crate::{
     container_of,
-    device::{
-        self,
-        Bound, //
-    },
     devres::*,
+    dma,
     drm::{
         driver,
         gem,
@@ -253,13 +250,10 @@ pub fn vmap<const SIZE: usize>(&self) -> Result<VMapRef<'_, T, SIZE>> {
     /// Creates (if necessary) and returns an immutable reference to a scatter-gather table of DMA
     /// pages for this object.
     ///
-    /// This will pin the object in memory. It is expected that `dev` should be a pointer to the
-    /// same [`device::Device`] which `self` belongs to, otherwise this function will return
-    /// `Err(EINVAL)`.
-    pub fn sg_table<'a>(
-        &'a self,
-        dev: &'a device::Device<Bound>,
-    ) -> Result<&'a scatterlist::SGTable> {
+    /// This pins the object in memory. The DMA handle must belong to this object's parent
+    /// device, otherwise this function returns `Err(EINVAL)`.
+    pub fn sg_table<'a>(&'a self, dma: dma::Handle<'a>) -> Result<&'a scatterlist::SGTable> {
+        let dev = dma.device();
         let parent = self.dev().as_ref();
         if dev.as_raw() != parent.as_ref().as_raw() {
             return Err(EINVAL);
@@ -576,6 +570,7 @@ unsafe impl<T: DriverObject> Sync for SGTableMap<T> {}
 mod tests {
     use super::*;
     use crate::{
+        device,
         drm::{
             self,
             UnregisteredDevice, //
@@ -702,14 +697,14 @@ fn vmap_io() -> Result {
     fn fail_sg_table_on_wrong_dev() -> Result {
         let (_dev, drm) = create_drm_dev()?;
         let reg = faux::Registration::new(c"EvilKunit", None)?;
-        let wrong_dev = reg.as_ref();
+        let wrong_dma = dma::Handle::new_for_test(reg.as_ref().as_ref());
 
         let obj = Object::<KunitObject>::new(&drm, PAGE_SIZE, ObjectConfig::default(), ())?;
 
-        assert_eq!(obj.sg_table(wrong_dev.as_ref()).err().unwrap(), EINVAL);
+        assert_eq!(obj.sg_table(wrong_dma).err().unwrap(), EINVAL);
 
         // If sgt_res was not initialized mistakenly with the wrong device, this should still fail.
-        assert_eq!(obj.sg_table(wrong_dev.as_ref()).err().unwrap(), EINVAL);
+        assert_eq!(obj.sg_table(wrong_dma).err().unwrap(), EINVAL);
 
         // TODO: Someday, we should test that creating an sg_table here still succeeds.
 
-- 
2.51.2


^ permalink raw reply	[flat|nested] 11+ messages in thread

* [RFC PATCH v2 10/10] rust: dma: remove the Device trait and its setters
  2026-11-29 22:24 [RFC PATCH v2 00/10] rust: dma: require device configuration before DMA Matteo Kloiber
                   ` (8 preceding siblings ...)
  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 ` Matteo Kloiber
  9 siblings, 0 replies; 11+ messages in thread
From: Matteo Kloiber @ 2026-11-29 22:24 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot, Alice Ryhl, Abdiel Janulgue,
	Robin Murphy, Andreas Hindborg, Gary Guo
  Cc: Daniel Almeida, Miguel Ojeda, David Airlie, Simona Vetter,
	Bjorn Helgaas, Krzysztof Wilczyński, Greg Kroah-Hartman,
	rust-for-linux, driver-core, dri-devel, nova-gpu, linux-kernel,
	Matteo Kloiber

All drivers configure DMA through dma::Setup now, and nothing calls the
unsafe dma::Device setters anymore. Keeping them would allow changing
the DMA parameters behind an existing dma::Handle.

Remove the trait, its PCI and platform implementations, and the
dma_set_mask_and_coherent() helper, which only the trait used.

With the setters gone, a driver can only change the DMA parameters
through its dma::Setup, and all Rust DMA APIs require the dma::Handle
that configure() returns. Update the safety comments of the PCI and
platform probe callbacks accordingly.

Signed-off-by: Matteo Kloiber <kernel@matt3o12.de>
---
 rust/helpers/dma.c      |  6 ---
 rust/kernel/dma.rs      | 83 +----------------------------------------
 rust/kernel/pci.rs      |  5 +--
 rust/kernel/platform.rs |  5 +--
 4 files changed, 5 insertions(+), 94 deletions(-)

diff --git a/rust/helpers/dma.c b/rust/helpers/dma.c
index ff8f24dae9df..443360237606 100644
--- a/rust/helpers/dma.c
+++ b/rust/helpers/dma.c
@@ -17,12 +17,6 @@ __rust_helper void rust_helper_dma_free_attrs(struct device *dev, size_t size,
 	dma_free_attrs(dev, size, cpu_addr, dma_handle, attrs);
 }
 
-__rust_helper int rust_helper_dma_set_mask_and_coherent(struct device *dev,
-							u64 mask)
-{
-	return dma_set_mask_and_coherent(dev, mask);
-}
-
 __rust_helper int rust_helper_dma_set_mask(struct device *dev, u64 mask)
 {
 	return dma_set_mask(dev, mask);
diff --git a/rust/kernel/dma.rs b/rust/kernel/dma.rs
index 226d00397f56..6b06f57bbdd2 100644
--- a/rust/kernel/dma.rs
+++ b/rust/kernel/dma.rs
@@ -9,8 +9,7 @@
     debugfs,
     device::{
         self,
-        Bound,
-        Core, //
+        Bound, //
     },
     error::to_result,
     fs::file,
@@ -178,86 +177,6 @@ pub(crate) fn new_for_test(dev: &'bound device::Device<Bound>) -> Self {
     }
 }
 
-/// Trait to be implemented by DMA capable bus devices.
-///
-/// The [`dma::Device`](Device) trait should be implemented by bus specific device representations,
-/// where the underlying bus is DMA capable, such as:
-#[cfg_attr(CONFIG_PCI, doc = "* [`pci::Device`](kernel::pci::Device)")]
-/// * [`platform::Device`](::kernel::platform::Device)
-pub trait Device<'a>: AsRef<device::Device<Core<'a>>> {
-    /// Set up the device's DMA streaming addressing capabilities.
-    ///
-    /// This method is usually called once from `probe()` as soon as the device capabilities are
-    /// known.
-    ///
-    /// # Safety
-    ///
-    /// This method must not be called concurrently with any DMA allocation or mapping primitives,
-    /// such as [`Coherent::zeroed`].
-    unsafe fn dma_set_mask(&self, mask: DmaMask) -> Result {
-        // SAFETY:
-        // - By the type invariant of `device::Device`, `self.as_ref().as_raw()` is valid.
-        // - The safety requirement of this function guarantees that there are no concurrent calls
-        //   to DMA allocation and mapping primitives using this mask.
-        to_result(unsafe { bindings::dma_set_mask(self.as_ref().as_raw(), mask.value()) })
-    }
-
-    /// Set up the device's DMA coherent addressing capabilities.
-    ///
-    /// This method is usually called once from `probe()` as soon as the device capabilities are
-    /// known.
-    ///
-    /// # Safety
-    ///
-    /// This method must not be called concurrently with any DMA allocation or mapping primitives,
-    /// such as [`Coherent::zeroed`].
-    unsafe fn dma_set_coherent_mask(&self, mask: DmaMask) -> Result {
-        // SAFETY:
-        // - By the type invariant of `device::Device`, `self.as_ref().as_raw()` is valid.
-        // - The safety requirement of this function guarantees that there are no concurrent calls
-        //   to DMA allocation and mapping primitives using this mask.
-        to_result(unsafe { bindings::dma_set_coherent_mask(self.as_ref().as_raw(), mask.value()) })
-    }
-
-    /// Set up the device's DMA addressing capabilities.
-    ///
-    /// This is a combination of [`Device::dma_set_mask`] and [`Device::dma_set_coherent_mask`].
-    ///
-    /// This method is usually called once from `probe()` as soon as the device capabilities are
-    /// known.
-    ///
-    /// # Safety
-    ///
-    /// This method must not be called concurrently with any DMA allocation or mapping primitives,
-    /// such as [`Coherent::zeroed`].
-    unsafe fn dma_set_mask_and_coherent(&self, mask: DmaMask) -> Result {
-        // SAFETY:
-        // - By the type invariant of `device::Device`, `self.as_ref().as_raw()` is valid.
-        // - The safety requirement of this function guarantees that there are no concurrent calls
-        //   to DMA allocation and mapping primitives using this mask.
-        to_result(unsafe {
-            bindings::dma_set_mask_and_coherent(self.as_ref().as_raw(), mask.value())
-        })
-    }
-
-    /// Set the maximum size of a single DMA segment the device may request.
-    ///
-    /// This method is usually called once from `probe()` as soon as the device capabilities are
-    /// known.
-    ///
-    /// # Safety
-    ///
-    /// This method must not be called concurrently with any DMA allocation or mapping primitives,
-    /// such as [`Coherent::zeroed`].
-    unsafe fn dma_set_max_seg_size(&self, size: u32) {
-        // SAFETY:
-        // - By the type invariant of `device::Device`, `self.as_ref().as_raw()` is valid.
-        // - The safety requirement of this function guarantees that there are no concurrent calls
-        //   to DMA allocation and mapping primitives using this parameter.
-        unsafe { bindings::dma_set_max_seg_size(self.as_ref().as_raw(), size) }
-    }
-}
-
 /// A DMA mask that holds a bitmask with the lowest `n` bits set.
 ///
 /// Use [`DmaMask::new`] or [`DmaMask::try_new`] to construct a value. Values
diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs
index 10b00b641dea..a98fbc252cd2 100644
--- a/rust/kernel/pci.rs
+++ b/rust/kernel/pci.rs
@@ -150,7 +150,8 @@ extern "C" fn probe_callback(
         from_result(|| {
             // 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.
+            // yet. The driver cannot use the Rust DMA allocation or mapping APIs until it
+            // consumes the token, and has no other way to change the DMA parameters.
             let dma = unsafe { dma::Setup::new(pdev.as_ref()) };
             let data = T::probe(pdev, InitTokens { dma }, info);
 
@@ -839,8 +840,6 @@ unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx>
 kernel::impl_device_context_deref!(unsafe { Device });
 kernel::impl_device_context_into_aref!(Device);
 
-impl<'a> crate::dma::Device<'a> for Device<device::Core<'a>> {}
-
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
     #[inline]
diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs
index bdb2c5c09b21..a24114c212bf 100644
--- a/rust/kernel/platform.rs
+++ b/rust/kernel/platform.rs
@@ -107,7 +107,8 @@ extern "C" fn probe_callback(pdev: *mut bindings::platform_device) -> kernel::ff
         from_result(|| {
             // 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.
+            // yet. The driver cannot use the Rust DMA allocation or mapping APIs until it
+            // consumes the token, and has no other way to change the DMA parameters.
             let dma = unsafe { dma::Setup::new(pdev.as_ref()) };
             let data = T::probe(pdev, InitTokens { dma }, info);
 
@@ -547,8 +548,6 @@ pub fn optional_irq_by_name(&self, name: &CStr) -> Result<IrqRequest<'_>> {
 kernel::impl_device_context_deref!(unsafe { Device });
 kernel::impl_device_context_into_aref!(Device);
 
-impl<'a> crate::dma::Device<'a> for Device<device::Core<'a>> {}
-
 // SAFETY: Instances of `Device` are always reference-counted.
 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
     fn inc_ref(&self) {
-- 
2.51.2


^ permalink raw reply	[flat|nested] 11+ messages in thread

end of thread, other threads:[~2026-11-29 22:25 UTC | newest]

Thread overview: 11+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
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 ` [RFC PATCH v2 02/10] rust: dma: add Setup, Params and Handle Matteo Kloiber
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

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®