From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=91.216.248.203 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795991105; b=KP+3T11AuG9+TSikkPF8vicrSqXgudHadVcR8gvrEj14z7vvXtCWIgLCbaxeAJcK8mBr jR6GaV8h/7f5ZGZ6/oKBHQQX9aRpyepqaypG6xcOgvDKIa5WtPDPqIi45FtX4LIcqeJRH tAoKST5fd2QBBRQqVQYqlDcbAQlvQfzm45FjMiJ6oSI96hSIz6NgqPkwSBKDW/BUqJEdn UXE57LKq5e3mrDXb+m60lJZQH7JlaDXUk5KJmfkKrIMOgJCNvrT/OZYNqryQpHUEjmS7F y7WxkMPBwDQKLnU0rS9jZCuVSXrop4piClY33M4+fYhwQwJNLm7bSn3SYzeJgDD4YbQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795991105; h=DMARC-Filter:From:DKIM-Signature:To:Cc:Subject:Date:Message-ID: X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding; bh=yDczlajYia02m4hKyaGTGtNwbOXz7oom5x4XXitnWCk=; b=sMvcvjUSGeXyAf52jCtTnPUme50Wr+aYj5SBOGF+gugRkmExTgCT1Plz7jrHyAb7epoC /1IP5t1gH1qNN5F+rDIdavGg+X7PauceJ+HWj7RluwFCkK/Hr4+s/oyHG/v3oqg9BqtFG 7dF2/w1IaFbNwgsmyX2LO0mdeJvWQhQK2EMkCl/RBYTJLKXC4pINykYtw08zzu3wm/Yxn eMHTprseLhLGzeYVIIdAa1IoRRlGR0/ZuLYj36E+p5GkHUoPkKfmTtCiOwzXQ6LIhp9xy 9oCe4ELUbQ6jr5Ayo1u+kz39mlZSsh0SRY/4gBnGsT9qwx1gSHNo5WJQD12HnmVedBQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=matt3o12.de; spf=pass smtp.mailfrom=matt3o12.de; dkim=pass header.d=matt3o12.de header.i=@matt3o12.de header.a=rsa-sha256 header.s=securedbylima-20230709 header.b=T5EtLDLK; arc=none smtp.remote-ip=91.216.248.203 Received: from mx1.mail-out.lima-city.de (mx1.mail-out.lima-city.de [91.216.248.203]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id BA054606A32F; Sun, 29 Nov 2026 22:25:04 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org BA054606A32F Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=matt3o12.de Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=matt3o12.de Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=matt3o12.de header.i=@matt3o12.de header.a=rsa-sha256 header.s=securedbylima-20230709 header.b=T5EtLDLK From: Matteo Kloiber DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=matt3o12.de; s=securedbylima-20230709; t=1795991096; bh=wkwq0cIggqoL68hPsKnOf84ct1xnnoIyDAWNQrP6pP4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=T5EtLDLKL3zzFZ7fljjOEuJS+st2Tcbjp38wKo7rbKVW5RllvbTUMhBNyls1wvBV/ vu36vvl2ctiMxFzEyQU1rsE0RAO+PzIAvZzov6H6HxxiHos4dxRLmeXSEiunq1bht4 pkJgW9eEXjd3DINJDxvxFMnfih3gb3mM3t3rAsxjP5KlBYR8JqBkMe8oGX1/0V9UTK 3mJOgr5gCXoKVTKYro8gv7p8bam66tT82EQLRJW4U+9zSOHoPsh9Zb0IVi/wWr4cco vl/7k/b4Q1BSItEbbaN6emr5zS3b/aP4O/b2eYG1elz/Vd9+f58P20IDApiARSJEW8 494P7oD8OEIuA== 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 , =?UTF-8?q?Krzysztof=20Wilczy=C5=84ski?= , Greg Kroah-Hartman , rust-for-linux@vger.kernel.org, driver-core@lists.linux.dev, dri-devel@lists.freedesktop.org, nova-gpu@lists.linux.dev, linux-kernel@vger.kernel.org, Matteo Kloiber Subject: [RFC PATCH v2 02/10] rust: dma: add Setup, Params and Handle Date: Sun, 29 Nov 2026 23:24:21 +0100 Message-ID: <20261129222429.2380652-3-kernel@matt3o12.de> X-Mailer: git-send-email 2.51.2 In-Reply-To: <20261129222429.2380652-1-kernel@matt3o12.de> References: <20261129222429.2380652-1-kernel@matt3o12.de> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: 8bit 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 Link: https://lore.kernel.org/DLHH0K25NLX5.616R4D860TXU@nvidia.com Link: https://lore.kernel.org/DLR1JCUWS824.35QJU45D2W9ZE@nvidia.com Signed-off-by: Matteo Kloiber --- 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::::zeroed(dma.device(), GFP_KERNEL)?; +/// # Ok::<(), Error>(()) } +/// ``` +pub struct Params { + /// Address mask for streaming DMA mappings. + pub streaming_mask: Option, + /// Address mask for coherent DMA allocations. + pub coherent_mask: Option, + /// 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, +} + +/// 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, +} + +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) -> 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> { + 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, +} + +impl<'bound> Handle<'bound> { + /// Returns the device associated with this DMA handle. + #[inline] + pub fn device(self) -> &'bound device::Device { + 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::() }; 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>, 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 { ::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>, tokens: InitTokens<'bound>, -- 2.51.2