dma::Coherent & dma::CoherentInit API
Subsystems (6)
Danilo Krummrich
maintainercover dma::Coherent & dma::CoherentInit API
This patch series introduces the dma::Coherent API Gary worked out in the context of his I/O projection work.
Additionally, introduce dma::CoherentInit, a type that encapsulates a dma::Coherent object before its DMA address is exposed to the device. dma::CoherentInit can guarantee exclusive access to the inner dma::Coherent object and implement Deref and DerefMut.
Also add Coherent::init() and Coherent::init_with_attrs() so we can directly initialize a new dma::Coherent object through an impl Init<T, E>.
Danilo Krummrich (5):
rust: dma: use "kernel vertical" style for imports
rust: dma: introduce dma::CoherentInit for memory initialization
rust: dma: add Coherent:init() and Coherent::init_with_attrs()
gpu: nova-core: use Coherent::init to initialize GspFwWprMeta
gpu: nova-core: convert Gsp::new() to use CoherentInit
Gary Guo (3):
rust: dma: add generalized container for types other than slices
rust: dma: add zeroed constructor to Coherent
gpu: nova-core: convert to new dma::Coherent API
drivers/gpu/nova-core/dma.rs | 19 +- drivers/gpu/nova-core/falcon.rs | 7 +- drivers/gpu/nova-core/firmware.rs | 10 +- drivers/gpu/nova-core/gsp.rs | 65 ++-- drivers/gpu/nova-core/gsp/boot.rs | 7 +- drivers/gpu/nova-core/gsp/cmdq.rs | 55 +-- drivers/gpu/nova-core/gsp/fw.rs | 82 ++-- rust/kernel/device.rs | 4 +- rust/kernel/dma.rs | 626 +++++++++++++++++++++++------- samples/rust/rust_dma.rs | 8 +- 10 files changed, 619 insertions(+), 264 deletions(-)
base-commit: 1195fcbda62f12108dc9be56fa4173897905b90c
Signature · 1 line
2.53.0
Danilo Krummrich
maintainerPATCH 1/8 rust: dma: use "kernel vertical" style for imports
Convert all imports to use "kernel vertical" style.
With this, subsequent patches neither introduce unrelated changes nor leave an inconsistent import pattern.
While at it, drop unnecessary imports covered by prelude::*.
--- rust/kernel/dma.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-)
rust/kernel/dma.rs +12 -4
@@ -5,12 +5,20 @@//! C header: [`include/linux/dma-mapping.h`](srctree/include/linux/dma-mapping.h) use crate ::{ - bindings, build_assert, device, - device::{Bound ,Core }, - error::{to_result,Result }, + bindings, + build_assert, + device::{ + self, +Bound , +Core ,// + }, + error::to_result, prelude::*, sync::aref::ARef , - transmute::{AsBytes ,FromBytes }, + transmute::{ +AsBytes , +FromBytes ,// + },// };use core::ptr::NonNull ;
Signature · 1 line
2.53.0
Re: [PATCH 1/8] rust: dma: use "kernel vertical" style for imports
Quoted 9 lines · Danilo Krummrich
Convert all imports to use "kernel vertical" style.
With this, subsequent patches neither introduce unrelated changes nor leave an inconsistent import pattern.
While at it, drop unnecessary imports covered by prelude::*.
Quoted 3 lines
--- rust/kernel/dma.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-)
Danilo Krummrich
maintainerPATCH 2/8 rust: dma: add generalized container for types other than slices
In reply to Danilo KrummrichFrom: Gary Guo <[email protected]>
Currently, CoherentAllocation is concecptually a DMA coherent container of a slice of [T] of runtime-checked length. Generalize it by creating dma::Coherent<T> which can hold any value of T. Coherent::alloc_with_attrs is implemented but not yet exposed, as I believe we should not expose the way to obtain an uninitialized coherent region.
Coherent<[T]> provides a len method instead of the previous count() method to be consistent with methods on slices.
The existing type is re-defined as a type alias of Coherent<[T]> to ease transition. Methods in use are not yet removed.
--- rust/kernel/device.rs | 4 +- rust/kernel/dma.rs | 361 ++++++++++++++++++++++++++---------------- 2 files changed, 226 insertions(+), 139 deletions(-)
rust/kernel/device.rs +2 -2
@@ -575,7 +575,7 @@ pub trait DeviceContext: private::Sealed {}/// The bound context indicates that for the entire duration of the lifetime of a [`Device<Bound>`] /// reference, the [`Device`] is guaranteed to be bound to a driver. /// -/// Some APIs, such as [`dma::CoherentAllocation`] or [`Devres`] rely on the [`Device`] to be bound, +/// Some APIs, such as [`dma::Coherent`] or [`Devres`] rely on the [`Device`] to be bound, /// which can be proven with the [`Bound`] device context. /// /// Any abstraction that can guarantee a scope where the corresponding bus device is bound, should
@@ -584,7 +584,7 @@ pub trait DeviceContext: private::Sealed {}/// /// [`Devres`]: kernel::devres::Devres /// [`Devres::access`]: kernel::devres::Devres::access -/// [`dma::CoherentAllocation`]: kernel::dma::CoherentAllocation +/// [`dma::Coherent`]: kernel::dma::Coherent pub struct Bound ;mod private {
rust/kernel/dma.rs +224 -137
532 lines not on this page · raw message
Signature · 1 line
2.53.0
Re: [PATCH 2/8] rust: dma: add generalized container for types other than slices
Quoted 9 lines · Danilo Krummrich
From: Gary Guo <[email protected]>
Currently,
CoherentAllocationis concecptually a DMA coherent container of a slice of[T]of runtime-checked length. Generalize it by creatingdma::Coherent<T>which can hold any value ofT.Coherent::alloc_with_attrsis implemented but not yet exposed, as I believe we should not expose the way to obtain an uninitialized coherent region.
Quoted 8 lines
Coherent<[T]>provides alenmethod instead of the previouscount()method to be consistent with methods on slices.The existing type is re-defined as a type alias of
Coherent<[T]>to ease transition. Methods in use are not yet removed.Signed-off-by Gary Guo <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>
I see you have both size() and len(). I think it would be clearer to rename size() to len_bytes().
Otherwise LGTM.
Alice
Gary Guo
reviewerRe: [PATCH 2/8] rust: dma: add generalized container for types other than slices
Quoted 13 lines · Alice Ryhl
Quoted 12 lines · Danilo Krummrich
From: Gary Guo <[email protected]>
Currently,
CoherentAllocationis concecptually a DMA coherent container of a slice of[T]of runtime-checked length. Generalize it by creatingdma::Coherent<T>which can hold any value ofT.Coherent::alloc_with_attrsis implemented but not yet exposed, as I believe we should not expose the way to obtain an uninitialized coherent region.
Coherent<[T]>provides alenmethod instead of the previouscount()method to be consistent with methods on slices.
Quoted 8 lines
Quoted 5 lines
The existing type is re-defined as a type alias of
Coherent<[T]>to ease transition. Methods in use are not yet removed.Signed-off-by Gary Guo <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>I see you have both
size()andlen(). I think it would be clearer to renamesize()tolen_bytes().
This is an API that already exists and I simply moved it around so it is implemented for all types, not just [T].
I also think that size() quite unambiguously means the size in bytes (like, in all allocation and I/O APIs, size means size of object in bytes); I don't see much benefit in renaming it len_bytes.
Best,
Gary
Quoted 5 lines
Otherwise LGTM.
Reviewed-by Alice Ryhl <[email protected]>Alice
Alexandre Courbot
maintainerRe: [PATCH 2/8] rust: dma: add generalized container for types other than slices
Quoted 23 lines · Gary Guo
Quoted 13 lines · Alice Ryhl
Quoted 12 lines · Danilo Krummrich
From: Gary Guo <[email protected]>
Currently,
CoherentAllocationis concecptually a DMA coherent container of a slice of[T]of runtime-checked length. Generalize it by creatingdma::Coherent<T>which can hold any value ofT.Coherent::alloc_with_attrsis implemented but not yet exposed, as I believe we should not expose the way to obtain an uninitialized coherent region.
Coherent<[T]>provides alenmethod instead of the previouscount()method to be consistent with methods on slices.Quoted 8 lines
Quoted 5 lines
The existing type is re-defined as a type alias of
Coherent<[T]>to ease transition. Methods in use are not yet removed.Signed-off-by Gary Guo <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>I see you have both
size()andlen(). I think it would be clearer to renamesize()tolen_bytes().
Quoted 6 lines
This is an API that already exists and I simply moved it around so it is implemented for all types, not just
[T].I also think that
size()quite unambiguously means the size in bytes (like, in all allocation and I/O APIs,sizemeans size of object in bytes); I don't see much benefit in renaming itlen_bytes.
Agreed, furthermore len is used in the standard library so the pattern of it returning a number of elements is pretty established.
Generally speaking I tend to prefer having the units mentioned in the doccomment rather than the method name.
Danilo Krummrich
maintainerPATCH 3/8 rust: dma: add zeroed constructor to `Coherent`
In reply to Danilo KrummrichFrom: Gary Guo <[email protected]>
These constructors create a coherent container of a single object instead of slice. They are named zeroed and zeroed_with_attrs to emphasis that they are created initialized zeroed. It is intended that there'll be new constructors that take PinInit instead of zeroing.
--- rust/kernel/dma.rs | 77 +++++++++++++++++++++++++++++++++++----- samples/rust/rust_dma.rs | 8 ++--- 2 files changed, 73 insertions(+), 12 deletions(-)
rust/kernel/dma.rs +69 -8
@@ -47,7 +47,7 @@ pub trait Device: AsRef<device::Device<Core>> {/// # Safety /// /// This method must not be called concurrently with any DMA allocation or mapping primitives, -/// such as [`CoherentAllocation::alloc_attrs`]. +/// 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.
@@ -64,7 +64,7 @@ unsafe fn dma_set_mask(&self, mask: DmaMask) -> Result {/// # Safety /// /// This method must not be called concurrently with any DMA allocation or mapping primitives, -/// such as [`CoherentAllocation::alloc_attrs`]. +/// 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.
@@ -83,7 +83,7 @@ unsafe fn dma_set_coherent_mask(&self, mask: DmaMask) -> Result {/// # Safety /// /// This method must not be called concurrently with any DMA allocation or mapping primitives, -/// such as [`CoherentAllocation::alloc_attrs`]. +/// 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.
@@ -102,7 +102,7 @@ unsafe fn dma_set_mask_and_coherent(&self, mask: DmaMask) -> Result {/// # Safety /// /// This method must not be called concurrently with any DMA allocation or mapping primitives, -/// such as [`CoherentAllocation::alloc_attrs`]. +/// 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.
@@ -202,12 +202,12 @@ pub const fn value(&self) -> u64 {/// /// ``` /// # use kernel::device::{Bound, Device}; -/// use kernel::dma::{attrs::*, CoherentAllocation}; +/// use kernel::dma::{attrs::*, Coherent}; /// /// # fn test(dev: &Device<Bound>) -> Result { /// let attribs = DMA_ATTR_FORCE_CONTIGUOUS | DMA_ATTR_NO_WARN; -/// let c: CoherentAllocation<u64> = -/// CoherentAllocation::alloc_attrs(dev, 4, GFP_KERNEL, attribs)?; +/// let c: Coherent<[u64]> = +/// Coherent::zeroed_slice_with_attrs(dev, 4, GFP_KERNEL, attribs)?; /// # Ok::<(), Error>(()) } /// ``` #[derive( Clone , Copy , PartialEq )]
@@ -492,7 +492,6 @@ pub unsafe fn field_write<F: AsBytes>(&self, field: *mut F, val: F) {impl <T :AsBytes +FromBytes >Coherent <T > {/// Allocates a region of `T` of coherent memory. -#[expect(unused)] fn alloc_with_attrs ( dev: &device::Device <Bound >, gfp_flags: kernel::alloc::Flags,
@@ -529,6 +528,33 @@ fn alloc_with_attrs( }) } +/// Allocates a region of type `T` of coherent memory. +/// +/// # Examples +/// +/// ``` +/// # use kernel::device::{Bound, Device}; +/// use kernel::dma::{attrs::*, Coherent}; +/// +/// # fn test(dev: &Device<Bound>) -> Result { +/// let c: Coherent<[u64; 4]> = +/// Coherent::zeroed_with_attrs(dev, GFP_KERNEL, DMA_ATTR_NO_WARN)?; +/// # Ok::<(), Error>(()) } +/// ``` +pub fn zeroed_with_attrs ( + dev: &device::Device <Bound >, + gfp_flags: kernel::alloc::Flags , + dma_attrs:Attrs , + ) ->Result <Self > { +Self ::alloc_with_attrs (dev, gfp_flags | __GFP_ZERO, dma_attrs) + } + +/// Performs the same functionality as [`Coherent::zeroed_with_attrs`], except the +/// `dma_attrs` is 0 by default. +pub fn zeroed (dev: &device::Device <Bound >, gfp_flags: kernel::alloc::Flags ) ->Result <Self > { +Self ::zeroed_with_attrs (dev, gfp_flags,Attrs (0 )) + } +/// Allocates a region of `[T; len]` of coherent memory. fn alloc_slice_with_attrs ( dev: &device::Device<Bound>,
@@ -572,6 +598,41 @@ fn alloc_slice_with_attrs( dma_attrs, }) } + +/// Allocates a zeroed region of type `T` of coherent memory. +/// +/// Unlike `Coherent::<[T; N]>::zeroed_with_attrs`, `Coherent::<T>::zeored_slices` support +/// a runtime length. +/// +/// # Examples +/// +/// ``` +/// # use kernel::device::{Bound, Device}; +/// use kernel::dma::{attrs::*, Coherent}; +/// +/// # fn test(dev: &Device<Bound>) -> Result { +/// let c: Coherent<[u64]> = +/// Coherent::zeroed_slice_with_attrs(dev, 4, GFP_KERNEL, DMA_ATTR_NO_WARN)?; +/// # Ok::<(), Error>(()) } +/// ``` +pub fn zeroed_slice_with_attrs ( + dev: &device::Device <Bound >, + len:usize , + gfp_flags: kernel::alloc::Flags , + dma_attrs:Attrs , + ) ->Result <Coherent <[T ]>> { +Coherent ::alloc_slice_with_attrs (dev, 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. +pub fn zeroed_slice ( + dev: &device::Device <Bound >, + len:usize , + gfp_flags: kernel::alloc::Flags , + ) ->Result <Coherent <[T ]>> { +Self ::zeroed_slice_with_attrs (dev, len, gfp_flags,Attrs (0 )) + } }impl <T :AsBytes +FromBytes >Coherent <[T ]> {
samples/rust/rust_dma.rs +4 -4
@@ -6,7 +6,7 @@use kernel::{ device::Core , - dma::{CoherentAllocation ,DataDirection ,Device ,DmaMask }, + dma::{Coherent ,DataDirection ,Device ,DmaMask }, page, pci, prelude::*, scatterlist::{Owned ,SGTable },
@@ -16,7 +16,7 @@#[pin_data( PinnedDrop )] struct DmaSampleDriver { pdev:ARef <pci::Device >, - ca:CoherentAllocation <MyStruct >, + ca:Coherent <[MyStruct ]>,#[pin] sgt:SGTable <Owned <VVec <u8 >>>, }
@@ -64,8 +64,8 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> impl PinInit<Self, E// SAFETY: There are no concurrent calls to DMA allocation and mapping primitives. unsafe { pdev.dma_set_mask_and_coherent (mask)? }; -let ca:CoherentAllocation <MyStruct > = -CoherentAllocation ::alloc_coherent (pdev.as_ref (),TEST_VALUES .len (),GFP_KERNEL )?; +let ca:Coherent <[MyStruct ]> = +Coherent ::zeroed_slice (pdev.as_ref (),TEST_VALUES .len (),GFP_KERNEL )?;for (i, value)in TEST_VALUES .into_iter ().enumerate () { kernel::dma_write!(ca, [i]?,MyStruct ::new (value.0 , value.1 ));
Signature · 1 line
2.53.0
Re: [PATCH 3/8] rust: dma: add zeroed constructor to `Coherent`
Quoted 9 lines · Danilo Krummrich
From: Gary Guo <[email protected]>
These constructors create a coherent container of a single object instead of slice. They are named
zeroedandzeroed_with_attrsto emphasis that they are created initialized zeroed. It is intended that there'll be new constructors that takePinInitinstead of zeroing.Signed-off-by Gary Guo <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>
Re: [PATCH 3/8] rust: dma: add zeroed constructor to `Coherent`
In reply to Danilo KrummrichOn Wed Mar 4, 2026 at 1:22 AM JST, Danilo Krummrich wrote:
<snip>
rust/kernel/dma.rs fn alloc_slice_with_attrs( · line 604
Quoted 8 lines
rust/kernel/dma.rs +4
-0@@ -572,6 +598,41 @@ fn alloc_slice_with_attrs( dma_attrs, }) } + +/// Allocates a zeroed region of type `T` of coherent memory. +/// +/// Unlike `Coherent::<[T; N]>::zeroed_with_attrs`, `Coherent::<T>::zeored_slices` support
s/zeored_slices/zeroed_slices
Otherwise,
Danilo Krummrich
maintainerPATCH 4/8 rust: dma: introduce dma::CoherentInit for memory initialization
In reply to Danilo KrummrichCurrently, dma::Coherent cannot safely provide (mutable) access to its underlying memory because the memory might be concurrently accessed by a DMA device. This makes it difficult to safely initialize the memory before handing it over to the hardware.
Introduce dma::CoherentInit, a type that encapsulates a dma::Coherent before its DMA address is exposed to the device. dma::CoherentInit can guarantee exclusive access to the inner dma::Coherent and implement Deref and DerefMut.
Once the memory is properly initialized, dma::CoherentInit can be converted into a regular dma::Coherent.
--- rust/kernel/dma.rs | 153 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 152 insertions(+), 1 deletion(-)
rust/kernel/dma.rs +152 -1
@@ -20,7 +20,13 @@ FromBytes, // }, // }; -use core::ptr::NonNull ; +use core::{ + ops::{ +Deref , +DerefMut ,// + }, + ptr::NonNull ,// +};/// DMA address type. ///
@@ -352,6 +358,151 @@ fn from(direction: DataDirection) -> Self { } } +/// Initializer type for [`Coherent`]. +/// +/// A [`Coherent`] object can't provide access to its memory as (mutable) slice safely, since it +/// can't fulfill the requirements for creating a slice. For instance, it is not valid to have a +/// (mutable) slice to of the memory of a [`Coherent`] while the memory might be accessed by a +/// device. +/// +/// In contrast, this initializer type is able to fulfill the requirements to safely obtain a +/// (mutable) slice, as it neither provides access to the DMA address of the embedded [`Coherent`], +/// nor can it be used with the DMA projection accessors. +/// +/// Once initialized, this type can be converted to a regular [`Coherent`] object. +/// +/// # Examples +/// +/// `CoherentInit<T>`: +/// +/// ``` +/// # use kernel::device::{ +/// # Bound, +/// # Device, +/// # }; +/// use kernel::dma::{attrs::*, +/// Coherent, +/// CoherentInit, +/// }; +/// +/// # fn test(dev: &Device<Bound>) -> Result { +/// let mut dmem: CoherentInit<u64> = +/// CoherentInit::zeroed_with_attrs(dev, GFP_KERNEL, DMA_ATTR_NO_WARN)?; +/// *dmem = 42; +/// let dmem: Coherent<u64> = dmem.into(); +/// # Ok::<(), Error>(()) } +/// ``` +/// +/// `CoherentInit<[T]>`: +/// +/// +/// ``` +/// # use kernel::device::{ +/// # Bound, +/// # Device, +/// # }; +/// use kernel::dma::{attrs::*, +/// Coherent, +/// CoherentInit, +/// }; +/// +/// # fn test(dev: &Device<Bound>) -> Result { +/// let mut dmem: CoherentInit<[u64]> = +/// CoherentInit::zeroed_slice_with_attrs(dev, 4, GFP_KERNEL, DMA_ATTR_NO_WARN)?; +/// dmem.fill(42); +/// let dmem: Coherent<[u64]> = dmem.into(); +/// # Ok::<(), Error>(()) } +/// ``` +pub struct CoherentInit <T :AsBytes +FromBytes +KnownSize + ?Sized >(Coherent <T >); + +impl <T :AsBytes +FromBytes >CoherentInit <[T ]> { +/// Initializer variant of [`Coherent::zeroed_slice_with_attrs`]. +pub fn zeroed_slice_with_attrs ( + dev: &device::Device <Bound >, + 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 ) + } + +/// Same as [CoherentInit::zeroed_slice_with_attrs], but with `dma::Attrs(0)`. +pub fn zeroed_slice ( + dev: &device::Device <Bound >, + count:usize , + gfp_flags: kernel::alloc::Flags , + ) ->Result <Self > { +Self ::zeroed_slice_with_attrs (dev, count, gfp_flags,Attrs (0 )) + } + +/// Initializes the element at `i` using the given initializer. +/// +/// Returns `EINVAL` if `i` is out of bounds. +pub fn init_at <E >(&mut self, i:usize , init:impl Init <T ,E >) ->Result +where +Error :From <E >, + { +if i >= self.0 .len () { +return Err (EINVAL ); + } + +let ptr = core::ptr::from_mut (&mut self[i]); + +// SAFETY: +// - `ptr` is valid, properly aligned, and within this allocation. +// - `T: AsBytes + FromBytes` guarantees all bit patterns are valid, so partial writes on +// error cannot leave the element in an invalid state. +// - The DMA address has not been exposed yet, so there is no concurrent device access. +unsafe { init.__init (ptr)? }; + +Ok (()) + } +} + +impl <T :AsBytes +FromBytes >CoherentInit <T > { +/// Same as [`CoherentInit::zeroed_slice_with_attrs`], but for a single element. +pub fn zeroed_with_attrs ( + dev: &device::Device <Bound >, + gfp_flags: kernel::alloc::Flags , + dma_attrs:Attrs , + ) ->Result <Self > { +Coherent ::zeroed_with_attrs (dev, gfp_flags, dma_attrs).map (Self ) + } + +/// Same as [`CoherentInit::zeroed_slice`], but for a single element. +pub fn zeroed (dev: &device::Device <Bound >, gfp_flags: kernel::alloc::Flags ) ->Result <Self > { +Self ::zeroed_with_attrs (dev, gfp_flags,Attrs (0 )) + } +} + +impl <T :AsBytes +FromBytes +KnownSize + ?Sized >Deref for CoherentInit <T > { +type Target =T ; + +fn deref (&self) -> &Self ::Target { +// SAFETY: +// - We have not exposed the DMA address yet, so there can't be any concurrent access by a +// device. +// - We have exclusive access to `self.0`. +unsafe { self.0 .as_ref () } + } +} + +impl <T :AsBytes +FromBytes +KnownSize + ?Sized >DerefMut for CoherentInit <T > { +fn deref_mut (&mut self) -> &mut Self ::Target { +// SAFETY: +// - We have not exposed the DMA address yet, so there can't be any concurrent access by a +// device. +// - We have exclusive access to `self.0`. +unsafe { self.0 .as_mut () } + } +} + +impl <T :AsBytes +FromBytes +KnownSize + ?Sized >From <CoherentInit <T >>for Coherent <T > { +fn from (value:CoherentInit <T >) ->Self { + value.0 + } +} +/// An abstraction of the `dma_alloc_coherent` API. /// /// This is an abstraction around the `dma_alloc_coherent` API which is used to allocate and map
Signature · 1 line
2.53.0
Gary Guo
reviewerRe: [PATCH 4/8] rust: dma: introduce dma::CoherentInit for memory initialization
Quoted 151 lines · Danilo Krummrich
Currently,
dma::Coherentcannot safely provide (mutable) access to its underlying memory because the memory might be concurrently accessed by a DMA device. This makes it difficult to safely initialize the memory before handing it over to the hardware.Introduce
dma::CoherentInit, a type that encapsulates adma::Coherentbefore its DMA address is exposed to the device.dma::CoherentInitcan guarantee exclusive access to the innerdma::Coherentand implement Deref and DerefMut.Once the memory is properly initialized,
dma::CoherentInitcan be converted into a regulardma::Coherent.Signed-off-by Danilo Krummrich <[email protected]>--- rust/kernel/dma.rs | 153 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 152 insertions(+), 1 deletion(-)rust/kernel/dma.rs +117
-1@@ -20,7 +20,13 @@ FromBytes, // }, // }; -use core::ptr::NonNull ; +use core::{ + ops::{ +Deref , +DerefMut ,// + }, + ptr::NonNull ,// +};/// DMA address type. /// @@ -352,6 +358,151 @@ fn from(direction: DataDirection) -> Self { } } +/// Initializer type for [`Coherent`]. +/// +/// A [`Coherent`] object can't provide access to its memory as (mutable) slice safely, since it +/// can't fulfill the requirements for creating a slice. For instance, it is not valid to have a +/// (mutable) slice to of the memory of a [`Coherent`] while the memory might be accessed by a +/// device. +/// +/// In contrast, this initializer type is able to fulfill the requirements to safely obtain a +/// (mutable) slice, as it neither provides access to the DMA address of the embedded [`Coherent`], +/// nor can it be used with the DMA projection accessors. +/// +/// Once initialized, this type can be converted to a regular [`Coherent`] object. +/// +/// # Examples +/// +/// `CoherentInit<T>`: +/// +/// ``` +/// # use kernel::device::{ +/// # Bound, +/// # Device, +/// # }; +/// use kernel::dma::{attrs::*, +/// Coherent, +/// CoherentInit, +/// }; +/// +/// # fn test(dev: &Device<Bound>) -> Result { +/// let mut dmem: CoherentInit<u64> = +/// CoherentInit::zeroed_with_attrs(dev, GFP_KERNEL, DMA_ATTR_NO_WARN)?; +/// *dmem = 42; +/// let dmem: Coherent<u64> = dmem.into(); +/// # Ok::<(), Error>(()) } +/// ``` +/// +/// `CoherentInit<[T]>`: +/// +/// +/// ``` +/// # use kernel::device::{ +/// # Bound, +/// # Device, +/// # }; +/// use kernel::dma::{attrs::*, +/// Coherent, +/// CoherentInit, +/// }; +/// +/// # fn test(dev: &Device<Bound>) -> Result { +/// let mut dmem: CoherentInit<[u64]> = +/// CoherentInit::zeroed_slice_with_attrs(dev, 4, GFP_KERNEL, DMA_ATTR_NO_WARN)?; +/// dmem.fill(42); +/// let dmem: Coherent<[u64]> = dmem.into(); +/// # Ok::<(), Error>(()) } +/// ``` +pub struct CoherentInit <T :AsBytes +FromBytes +KnownSize + ?Sized >(Coherent <T >); + +impl <T :AsBytes +FromBytes >CoherentInit <[T ]> { +/// Initializer variant of [`Coherent::zeroed_slice_with_attrs`]. +pub fn zeroed_slice_with_attrs ( + dev: &device::Device <Bound >, + 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 ) + } + +/// Same as [CoherentInit::zeroed_slice_with_attrs], but with `dma::Attrs(0)`. +pub fn zeroed_slice ( + dev: &device::Device <Bound >, + count:usize , + gfp_flags: kernel::alloc::Flags , + ) ->Result <Self > { +Self ::zeroed_slice_with_attrs (dev, count, gfp_flags,Attrs (0 )) + } + +/// Initializes the element at `i` using the given initializer. +/// +/// Returns `EINVAL` if `i` is out of bounds. +pub fn init_at <E >(&mut self, i:usize , init:impl Init <T ,E >) ->Result +where +Error :From <E >, + { +if i >= self.0 .len () { +return Err (EINVAL ); + } + +let ptr = core::ptr::from_mut (&mut self[i]); + +// SAFETY: +// - `ptr` is valid, properly aligned, and within this allocation. +// - `T: AsBytes + FromBytes` guarantees all bit patterns are valid, so partial writes on +// error cannot leave the element in an invalid state. +// - The DMA address has not been exposed yet, so there is no concurrent device access. +unsafe { init.__init (ptr)? }; + +Ok (()) + } +} + +impl <T :AsBytes +FromBytes >CoherentInit <T > { +/// Same as [`CoherentInit::zeroed_slice_with_attrs`], but for a single element. +pub fn zeroed_with_attrs ( + dev: &device::Device <Bound >, + gfp_flags: kernel::alloc::Flags , + dma_attrs:Attrs , + ) ->Result <Self > { +Coherent ::zeroed_with_attrs (dev, gfp_flags, dma_attrs).map (Self ) + }
rust/kernel/dma.rs fn from(direction: DataDirection) -> Self { · line 480
Quoted 10 lines
rust/kernel/dma.rs +10
-0+ +/// Same as [`CoherentInit::zeroed_slice`], but for a single element. +pub fn zeroed (dev: &device::Device <Bound >, gfp_flags: kernel::alloc::Flags ) ->Result <Self > { +Self ::zeroed_with_attrs (dev, gfp_flags,Attrs (0 )) + } +} + +impl <T :AsBytes +FromBytes +KnownSize + ?Sized >Deref for CoherentInit <T > { +type Target =T ; +
The deref impls should be #[inline].
Some other methods could be as well.
Best,
Gary
Quoted 28 lines
rust/kernel/dma.rs +25
-0+fn deref (&self) -> &Self ::Target { +// SAFETY: +// - We have not exposed the DMA address yet, so there can't be any concurrent access by a +// device. +// - We have exclusive access to `self.0`. +unsafe { self.0 .as_ref () } + } +} + +impl <T :AsBytes +FromBytes +KnownSize + ?Sized >DerefMut for CoherentInit <T > { +fn deref_mut (&mut self) -> &mut Self ::Target { +// SAFETY: +// - We have not exposed the DMA address yet, so there can't be any concurrent access by a +// device. +// - We have exclusive access to `self.0`. +unsafe { self.0 .as_mut () } + } +} + +impl <T :AsBytes +FromBytes +KnownSize + ?Sized >From <CoherentInit <T >>for Coherent <T > { +fn from (value:CoherentInit <T >) ->Self { + value.0 + } +} +/// An abstraction of the `dma_alloc_coherent` API. /// /// This is an abstraction around the `dma_alloc_coherent` API which is used to allocate and map
Re: [PATCH 4/8] rust: dma: introduce dma::CoherentInit for memory initialization
In reply to Danilo KrummrichQuoted 10 lines · Danilo Krummrich
Currently,
dma::Coherentcannot safely provide (mutable) access to its underlying memory because the memory might be concurrently accessed by a DMA device. This makes it difficult to safely initialize the memory before handing it over to the hardware.Introduce
dma::CoherentInit, a type that encapsulates adma::Coherentbefore its DMA address is exposed to the device.dma::CoherentInitcan guarantee exclusive access to the innerdma::Coherentand implement Deref and DerefMut.
Quoted 4 lines
Once the memory is properly initialized,
dma::CoherentInitcan be converted into a regulardma::Coherent.Signed-off-by Danilo Krummrich <[email protected]>
overall LGTM
Quoted 1 line
+ let ptr =
core::ptr::from_mut(&mut self[i]);
&raw mut self[i].
Alice
Danilo Krummrich
maintainerRe: [PATCH 4/8] rust: dma: introduce dma::CoherentInit for memory initialization
Quoted 11 lines · Alice Ryhl
Quoted 10 lines · Danilo Krummrich
Currently,
dma::Coherentcannot safely provide (mutable) access to its underlying memory because the memory might be concurrently accessed by a DMA device. This makes it difficult to safely initialize the memory before handing it over to the hardware.Introduce
dma::CoherentInit, a type that encapsulates adma::Coherentbefore its DMA address is exposed to the device.dma::CoherentInitcan guarantee exclusive access to the innerdma::Coherentand implement Deref and DerefMut.
Quoted 8 lines
Quoted 4 lines
Once the memory is properly initialized,
dma::CoherentInitcan be converted into a regulardma::Coherent.Signed-off-by Danilo Krummrich <[email protected]>overall LGTM
Reviewed-by Alice Ryhl <[email protected]>
Gary and me concluded that dma::CoherentBox would probably be a better name for what this structure represents. I.e. you can carry it around and use it similar to a "real" Box until it is converted to dma::Coherent in order to make it available to the device.
Is your RB still valid with this rename?
Quoted 5 lines
Quoted 1 line
+ let ptr =
core::ptr::from_mut(&mut self[i]);&raw mut self[i].
Alice
Alice Ryhl
maintainerRe: [PATCH 4/8] rust: dma: introduce dma::CoherentInit for memory initialization
Quoted 20 lines · Danilo Krummrich
Quoted 18 lines · Alice Ryhl
Quoted 10 lines · Danilo Krummrich
Currently,
dma::Coherentcannot safely provide (mutable) access to its underlying memory because the memory might be concurrently accessed by a DMA device. This makes it difficult to safely initialize the memory before handing it over to the hardware.Introduce
dma::CoherentInit, a type that encapsulates adma::Coherentbefore its DMA address is exposed to the device.dma::CoherentInitcan guarantee exclusive access to the innerdma::Coherentand implement Deref and DerefMut.Quoted 4 lines
Once the memory is properly initialized,
dma::CoherentInitcan be converted into a regulardma::Coherent.Signed-off-by Danilo Krummrich <[email protected]>overall LGTM
Quoted 8 lines
Quoted 1 line
Reviewed-by Alice Ryhl <[email protected]>Gary and me concluded that
dma::CoherentBoxwould probably be a better name for what this structure represents. I.e. you can carry it around and use it similar to a "real" Box until it is converted todma::Coherentin order to make it available to the device.Is your RB still valid with this rename?
Yes.
Alexandre Courbot
maintainerRe: [PATCH 4/8] rust: dma: introduce dma::CoherentInit for memory initialization
In reply to Danilo KrummrichOn Wed Mar 4, 2026 at 1:22 AM JST, Danilo Krummrich wrote:
<snip>
Quoted 24 lines
rust/kernel/dma.rs +20
-0@@ -352,6 +358,151 @@ fn from(direction: DataDirection) -> Self { } } +/// Initializer type for [`Coherent`]. +/// +/// A [`Coherent`] object can't provide access to its memory as (mutable) slice safely, since it +/// can't fulfill the requirements for creating a slice. For instance, it is not valid to have a +/// (mutable) slice to of the memory of a [`Coherent`] while the memory might be accessed by a +/// device. +/// +/// In contrast, this initializer type is able to fulfill the requirements to safely obtain a +/// (mutable) slice, as it neither provides access to the DMA address of the embedded [`Coherent`], +/// nor can it be used with the DMA projection accessors. +/// +/// Once initialized, this type can be converted to a regular [`Coherent`] object. +/// +/// # Examples +/// +/// `CoherentInit<T>`: +/// +/// ``` +/// # use kernel::device::{ +/// # Bound,
rust/kernel/dma.rs fn from(direction: DataDirection) -> Self { · line 390
Quoted 10 lines
rust/kernel/dma.rs +10
-0+/// # Device, +/// # }; +/// use kernel::dma::{attrs::*, +/// Coherent, +/// CoherentInit, +/// }; +/// +/// # fn test(dev: &Device<Bound>) -> Result { +/// let mut dmem: CoherentInit<u64> = +/// CoherentInit::zeroed_with_attrs(dev, GFP_KERNEL, DMA_ATTR_NO_WARN)?;
Since this is an example, shall we use the simpler CoherentInit::zeroed?
Quoted 11 lines
rust/kernel/dma.rs +11
-0+/// *dmem = 42; +/// let dmem: Coherent<u64> = dmem.into(); +/// # Ok::<(), Error>(()) } +/// ``` +/// +/// `CoherentInit<[T]>`: +/// +/// +/// ``` +/// # use kernel::device::{ +/// # Bound,
rust/kernel/dma.rs fn from(direction: DataDirection) -> Self { · line 411
Quoted 10 lines
rust/kernel/dma.rs +10
-0+/// # Device, +/// # }; +/// use kernel::dma::{attrs::*, +/// Coherent, +/// CoherentInit, +/// }; +/// +/// # fn test(dev: &Device<Bound>) -> Result { +/// let mut dmem: CoherentInit<[u64]> = +/// CoherentInit::zeroed_slice_with_attrs(dev, 4, GFP_KERNEL, DMA_ATTR_NO_WARN)?;
Same here.
Quoted 20 lines
rust/kernel/dma.rs +20
-0+/// dmem.fill(42); +/// let dmem: Coherent<[u64]> = dmem.into(); +/// # Ok::<(), Error>(()) } +/// ``` +pub struct CoherentInit <T :AsBytes +FromBytes +KnownSize + ?Sized >(Coherent <T >); + +impl <T :AsBytes +FromBytes >CoherentInit <[T ]> { +/// Initializer variant of [`Coherent::zeroed_slice_with_attrs`]. +pub fn zeroed_slice_with_attrs ( + dev: &device::Device <Bound >, + 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 ) + } + +/// Same as [CoherentInit::zeroed_slice_with_attrs], but with `dma::Attrs(0)`. +pub fn zeroed_slice ( + dev: &device::Device<Bound>,
rust/kernel/dma.rs fn from(direction: DataDirection) -> Self { · line 441
Quoted 10 lines
rust/kernel/dma.rs +10
-0+ count: usize, + gfp_flags: kernel::alloc::Flags, + ) -> Result<Self> { + Self::zeroed_slice_with_attrs(dev, count, gfp_flags, Attrs(0)) + } + + /// Initializes the element at `i` using the given initializer. + /// + /// Returns `EINVAL` if `i` is out of bounds. + pub fn init_at<E>(&mut self, i: usize, init: impl Init<T, E>) -> Result
Should this method be introduced in the next patch, or even in its own patch? It feels a bit out of place at this stage since the non-array CoherentInit doesn't have an equivalent.
I was also wondering whether we could have an init method that initializes all the elements without having to zero the whole array first, but I guess it might be a bit difficult to implement in a flexible enough way.
Danilo Krummrich
maintainerRe: [PATCH 4/8] rust: dma: introduce dma::CoherentInit for memory initialization
Quoted 7 lines · Alexandre Courbot
rust/kernel/dma.rs fn from(direction: DataDirection) -> Self { · line 390
Quoted 3 lines · Danilo Krummrich
rust/kernel/dma.rs +3
-0+/// # fn test(dev: &Device<Bound>) -> Result { +/// let mut dmem: CoherentInit<u64> = +/// CoherentInit::zeroed_with_attrs(dev, GFP_KERNEL, DMA_ATTR_NO_WARN)?; Since this is an example, shall we use the simpler
CoherentInit::zeroed?
Sure.
Quoted 8 lines
rust/kernel/dma.rs fn from(direction: DataDirection) -> Self { · line 441
Quoted 4 lines
rust/kernel/dma.rs +4
-0+/// Initializes the element at `i` using the given initializer. +/// +/// Returns `EINVAL` if `i` is out of bounds. +pub fn init_at <E >(&mut self, i:usize , init:impl Init <T ,E >) ->Result Should this method be introduced in the next patch, or even in its own patch? It feels a bit out of place at this stage since the non-array
CoherentInitdoesn't have an equivalent.
The non-slice variant doesn't need it.
I don't see an advantage creating a separate patch for this.
Quoted 4 lines
I was also wondering whether we could have an
initmethod that initializes all the elements without having to zero the whole array first, but I guess it might be a bit difficult to implement in a flexible enough way.
You have this in the next patch, Coherent::init() works with arrays.
Danilo Krummrich
maintainerPATCH 5/8 rust: dma: add Coherent:init() and Coherent::init_with_attrs()
In reply to Danilo KrummrichAnalogous to Coherent::zeroed() and Coherent::zeroed_with_attrs(), add Coherent:init() and Coherent::init_with_attrs() which both take an impl Init<T, E> argument initializing the DMA coherent memory.
Compared to CoherentInit, Coherent::init() is a one-shot constructor that runs an Init closure and immediately exposes the DMA handle, whereas CoherentInit is a multi-stage initializer that provides safe &mut T access by withholding the DMA address until converted to Coherent.
--- rust/kernel/dma.rs | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+)
rust/kernel/dma.rs +37 -0
@@ -706,6 +706,43 @@ pub fn zeroed(dev: &device::Device<Bound>, gfp_flags: kernel::alloc::Flags) -> RSelf ::zeroed_with_attrs (dev, 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: &device::Device <Bound >, + gfp_flags: kernel::alloc::Flags , + dma_attrs:Attrs , + init:impl Init <T ,E >, + ) ->Result <Self > +where +Error :From <E >, + { +let dmem =Self ::alloc_with_attrs (dev, gfp_flags, dma_attrs)?; +let ptr = dmem.as_mut_ptr (); + +// SAFETY: +// - `ptr` is valid, properly aligned, and points to exclusively owned memory. +// - If `__init` fails, `self` is dropped, which safely frees the underlying `Coherent`'s +// DMA memory. `T: AsBytes + FromBytes` ensures there are no complex `Drop` requirements +// we are bypassing. +unsafe { init.__init (ptr)? }; + +Ok (dmem) + } + +/// Same as [`Coherent::zeroed`], but instead of a zero-initialization the memory is initialized +/// with `init`. +pub fn init <E >( + dev: &device::Device <Bound >, + 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) + } +/// Allocates a region of `[T; len]` of coherent memory. fn alloc_slice_with_attrs ( dev: &device::Device<Bound>,
Signature · 1 line
2.53.0
Danilo Krummrich
maintainerPATCH 6/8 gpu: nova-core: use Coherent::init to initialize GspFwWprMeta
In reply to Danilo KrummrichConvert wpr_meta to use Coherent::init() and simplify the initialization. It also avoids a separate initialization of GspFwWprMeta on the stack.
--- drivers/gpu/nova-core/gsp/boot.rs | 7 ++----- drivers/gpu/nova-core/gsp/fw.rs | 20 +++++++++++++++----- 2 files changed, 17 insertions(+), 10 deletions(-)
drivers/gpu/nova-core/gsp/boot.rs +2 -5
@@ -2,8 +2,7 @@use kernel::{ device, - dma::CoherentAllocation , - dma_write, + dma::Coherent , io::poll::read_poll_timeout, pci, prelude::*,
@@ -155,9 +154,7 @@ pub(crate) fn boot( bar, )?; -let wpr_meta = -CoherentAllocation ::<GspFwWprMeta >::alloc_coherent (dev,1 ,GFP_KERNEL | __GFP_ZERO)?; -dma_write! (wpr_meta, [0 ]?,GspFwWprMeta ::new (&gsp_fw, &fb_layout)); +let wpr_meta =Coherent ::init (dev,GFP_KERNEL ,GspFwWprMeta ::new (&gsp_fw, &fb_layout))?; self.cmdq .send_command (bar, commands::SetSystemInfo ::new (pdev))?;
drivers/gpu/nova-core/gsp/fw.rs +15 -5
@@ -131,7 +131,9 @@ pub(crate) fn wpr_heap_size(&self, chipset: Chipset, fb_size: u64) -> u64 {/// Structure passed to the GSP bootloader, containing the framebuffer layout as well as the DMA /// addresses of the GSP bootloader and firmware. #[repr(transparent)] -pub (crate )struct GspFwWprMeta (bindings::GspFwWprMeta ); +pub (crate )struct GspFwWprMeta { + inner: bindings::GspFwWprMeta , +}// SAFETY: Padding is explicit and does not contain uninitialized data. unsafe impl AsBytes for GspFwWprMeta {}
@@ -144,10 +146,14 @@ unsafe impl FromBytes for GspFwWprMeta {} type GspFwWprMetaBootInfo = bindings::GspFwWprMeta__bindgen_ty_1__bindgen_ty_1; impl GspFwWprMeta { -/// Fill in and return a `GspFwWprMeta` suitable for booting `gsp_firmware` using the + /// Returns an initializer for a `GspFwWprMeta` suitable for booting `gsp_firmware` using the /// `fb_layout` layout. -pub (crate )fn new (gsp_firmware: &GspFirmware , fb_layout: &FbLayout ) ->Self { -Self (bindings::GspFwWprMeta { + pub(crate) fn new<'a>( + gsp_firmware: &'a GspFirmware, + fb_layout: &'a FbLayout, + ) -> impl Init<Self> + 'a { + #[allow(non_snake_case)] + let init_inner = init!(bindings::GspFwWprMeta { // CAST: we want to store the bits of `GSP_FW_WPR_META_MAGIC` unmodified. magic: bindings::GSP_FW_WPR_META_MAGIC as u64, revision: u64::from(bindings::GSP_FW_WPR_META_REVISION),
@@ -182,7 +188,11 @@ pub(crate) fn new(gsp_firmware: &GspFirmware, fb_layout: &FbLayout) -> Self { fbSize: fb_layout.fb.end - fb_layout.fb.start, vgaWorkspaceOffset: fb_layout.vga_workspace.start, vgaWorkspaceSize: fb_layout.vga_workspace.end - fb_layout.vga_workspace.start, - ..Default ::default () + ..Zeroable ::init_zeroed () + }); + +init! (GspFwWprMeta { + inner <- init_inner, }) } }
Signature · 1 line
2.53.0
Gary Guo
reviewerRe: [PATCH 6/8] gpu: nova-core: use Coherent::init to initialize GspFwWprMeta
Quoted 54 lines · Danilo Krummrich
Convert
wpr_metato useCoherent::init()and simplify the initialization. It also avoids a separate initialization of GspFwWprMeta on the stack.Signed-off-by Danilo Krummrich <[email protected]>--- drivers/gpu/nova-core/gsp/boot.rs | 7 ++----- drivers/gpu/nova-core/gsp/fw.rs | 20 +++++++++++++++----- 2 files changed, 17 insertions(+), 10 deletions(-)drivers/gpu/nova-core/gsp/boot.rs +2
-5@@ -2,8 +2,7 @@use kernel::{ device, - dma::CoherentAllocation , - dma_write, + dma::Coherent , io::poll::read_poll_timeout, pci, prelude::*,@@ -155,9 +154,7 @@ pub(crate) fn boot( bar, )?; -let wpr_meta = -CoherentAllocation ::<GspFwWprMeta >::alloc_coherent (dev,1 ,GFP_KERNEL | __GFP_ZERO)?; -dma_write! (wpr_meta, [0 ]?,GspFwWprMeta ::new (&gsp_fw, &fb_layout)); +let wpr_meta =Coherent ::init (dev,GFP_KERNEL ,GspFwWprMeta ::new (&gsp_fw, &fb_layout))?; self.cmdq .send_command (bar, commands::SetSystemInfo ::new (pdev))?;drivers/gpu/nova-core/gsp/fw.rs +3
-1@@ -131,7 +131,9 @@ pub(crate) fn wpr_heap_size(&self, chipset: Chipset, fb_size: u64) -> u64 {/// Structure passed to the GSP bootloader, containing the framebuffer layout as well as the DMA /// addresses of the GSP bootloader and firmware. #[repr(transparent)] -pub (crate )struct GspFwWprMeta (bindings::GspFwWprMeta ); +pub (crate )struct GspFwWprMeta { + inner: bindings::GspFwWprMeta , +}// SAFETY: Padding is explicit and does not contain uninitialized data. unsafe impl AsBytes for GspFwWprMeta {}@@ -144,10 +146,14 @@ unsafe impl FromBytes for GspFwWprMeta {}type GspFwWprMetaBootInfo = bindings::GspFwWprMeta__bindgen_ty_1__bindgen_ty_1 ;impl GspFwWprMeta {
drivers/gpu/nova-core/gsp/fw.rs unsafe impl FromBytes for GspFwWprMeta {} · line 155
Quoted 10 lines
drivers/gpu/nova-core/gsp/fw.rs +6
-3-/// Fill in and return a `GspFwWprMeta` suitable for booting `gsp_firmware` using the +/// Returns an initializer for a `GspFwWprMeta` suitable for booting `gsp_firmware` using the /// `fb_layout` layout. -pub (crate )fn new (gsp_firmware: &GspFirmware , fb_layout: &FbLayout ) ->Self { -Self (bindings::GspFwWprMeta { +pub (crate )fn new <'a>( + gsp_firmware: &'aGspFirmware , + fb_layout: &'aFbLayout , + ) ->impl Init <Self > + 'a { +#[allow(non_snake_case)]
I suppose this is from the field accessor generated?
@Benno we probably should add #[allow(nonstandard_style)] on the accessor generated.
Best,
Gary
Quoted 17 lines
drivers/gpu/nova-core/gsp/fw.rs +6
-1+ let init_inner = init!(bindings::GspFwWprMeta { // CAST: we want to store the bits of `GSP_FW_WPR_META_MAGIC` unmodified. magic: bindings::GSP_FW_WPR_META_MAGIC as u64, revision: u64::from(bindings::GSP_FW_WPR_META_REVISION),@@ -182,7 +188,11 @@ pub(crate) fn new(gsp_firmware: &GspFirmware, fb_layout: &FbLayout) -> Self { fbSize: fb_layout.fb.end - fb_layout.fb.start, vgaWorkspaceOffset: fb_layout.vga_workspace.start, vgaWorkspaceSize: fb_layout.vga_workspace.end - fb_layout.vga_workspace.start, - ..Default ::default () + ..Zeroable ::init_zeroed () + }); + +init! (GspFwWprMeta { + inner <- init_inner, }) } }
Re: [PATCH 6/8] gpu: nova-core: use Coherent::init to initialize GspFwWprMeta
In reply to Danilo KrummrichQuoted 5 lines · Danilo Krummrich
Convert
wpr_metato useCoherent::init()and simplify the initialization. It also avoids a separate initialization of GspFwWprMeta on the stack.Signed-off-by Danilo Krummrich <[email protected]>
Danilo Krummrich
maintainerPATCH 7/8 gpu: nova-core: convert Gsp::new() to use CoherentInit
In reply to Danilo KrummrichConvert libos (LibosMemoryRegionInitArgument) and rmargs (GspArgumentsPadded) to use CoherentInit / Coherent::init() and simplify the initialization. This also avoids separate initialization on the stack.
--- drivers/gpu/nova-core/gsp.rs | 47 +++++++++++-------------- drivers/gpu/nova-core/gsp/fw.rs | 62 +++++++++++++++++++++++---------- 2 files changed, 65 insertions(+), 44 deletions(-)
drivers/gpu/nova-core/gsp.rs +21 -26
@@ -5,10 +5,11 @@use kernel::{ device, dma::{ +Coherent ,CoherentAllocation , +CoherentInit ,DmaAddress ,// }, - dma_write, pci, prelude::*, transmute::AsBytes ,//
@@ -104,7 +105,7 @@ fn new(dev: &device::Device<device::Bound>) -> Result<Self> {#[pin_data] pub (crate )struct Gsp {/// Libos arguments. -pub (crate ) libos:CoherentAllocation <LibosMemoryRegionInitArgument >, +pub (crate ) libos:Coherent <[LibosMemoryRegionInitArgument ]>,/// Init log buffer. loginit:LogBuffer ,/// Interrupts log buffer.
@@ -114,7 +115,7 @@ pub(crate) struct Gsp {/// Command queue. pub(crate) cmdq: Cmdq,/// RM arguments. - rmargs: CoherentAllocation<GspArgumentsPadded>, + rmargs: Coherent<GspArgumentsPadded>, }impl Gsp {
@@ -123,34 +124,28 @@ pub(crate) fn new(pdev: &pci::Device<device::Bound>) -> impl PinInit<Self, Error pin_init::pin_init_scope (move || {let dev = pdev.as_ref (); +// Initialise the logging structures. The OpenRM equivalents are in: +// _kgspInitLibosLoggingStructures (allocates memory for buffers) +// kgspSetupLibosInitArgs_IMPL (creates pLibosInitArgs[] array) Ok (try_pin_init! (Self { - libos:CoherentAllocation ::<LibosMemoryRegionInitArgument >::alloc_coherent ( - dev, -GSP_PAGE_SIZE /size_of ::<LibosMemoryRegionInitArgument >(), -GFP_KERNEL | __GFP_ZERO, - )?, loginit:LogBuffer ::new (dev)?, logintr:LogBuffer ::new (dev)?, logrm:LogBuffer ::new (dev)?, cmdq:Cmdq ::new (dev)?, - rmargs:CoherentAllocation ::<GspArgumentsPadded >::alloc_coherent ( - dev, -1 , -GFP_KERNEL | __GFP_ZERO, - )?, - _: { -// Initialise the logging structures. The OpenRM equivalents are in: -// _kgspInitLibosLoggingStructures (allocates memory for buffers) -// kgspSetupLibosInitArgs_IMPL (creates pLibosInitArgs[] array) -dma_write! ( - libos, [0 ]?,LibosMemoryRegionInitArgument ::new ("LOGINIT" , &loginit.0 ) - ); -dma_write! ( - libos, [1 ]?,LibosMemoryRegionInitArgument ::new ("LOGINTR" , &logintr.0 ) - ); -dma_write! (libos, [2 ]?,LibosMemoryRegionInitArgument ::new ("LOGRM" , &logrm.0 )); -dma_write! (rmargs, [0 ]?.inner, fw::GspArgumentsCached ::new (cmdq)); -dma_write! (libos, [3 ]?,LibosMemoryRegionInitArgument ::new ("RMARGS" , rmargs)); + rmargs:Coherent ::init (dev,GFP_KERNEL ,GspArgumentsPadded ::new (cmdq))?, + libos: { +let mut libos =CoherentInit ::zeroed_slice ( + dev, +GSP_PAGE_SIZE /size_of ::<LibosMemoryRegionInitArgument >(), +GFP_KERNEL , + )?; + + libos.init_at (0 ,LibosMemoryRegionInitArgument ::new ("LOGINIT" , &loginit.0 ))?; + libos.init_at (1 ,LibosMemoryRegionInitArgument ::new ("LOGINTR" , &logintr.0 ))?; + libos.init_at (2 ,LibosMemoryRegionInitArgument ::new ("LOGRM" , &logrm.0 ))?; + libos.init_at (3 ,LibosMemoryRegionInitArgument ::new ("RMARGS" , rmargs))?; + + libos.into () }, })) })
drivers/gpu/nova-core/gsp/fw.rs +44 -18
130 lines not on this page · raw message
Signature · 1 line
2.53.0
Gary Guo
reviewerRe: [PATCH 7/8] gpu: nova-core: convert Gsp::new() to use CoherentInit
Quoted 118 lines · Danilo Krummrich
Convert libos (LibosMemoryRegionInitArgument) and rmargs (GspArgumentsPadded) to use CoherentInit /
Coherent::init()and simplify the initialization. This also avoids separate initialization on the stack.Signed-off-by Danilo Krummrich <[email protected]>--- drivers/gpu/nova-core/gsp.rs | 47 +++++++++++-------------- drivers/gpu/nova-core/gsp/fw.rs | 62 +++++++++++++++++++++++---------- 2 files changed, 65 insertions(+), 44 deletions(-)drivers/gpu/nova-core/gsp.rs +21
-26@@ -5,10 +5,11 @@use kernel::{ device, dma::{ +Coherent ,CoherentAllocation , +CoherentInit ,DmaAddress ,// }, - dma_write, pci, prelude::*, transmute::AsBytes ,// @@ -104,7 +105,7 @@ fn new(dev: &device::Device<device::Bound>) -> Result<Self> {#[pin_data] pub (crate )struct Gsp {/// Libos arguments. -pub (crate ) libos:CoherentAllocation <LibosMemoryRegionInitArgument >, +pub (crate ) libos:Coherent <[LibosMemoryRegionInitArgument ]>,/// Init log buffer. loginit:LogBuffer ,/// Interrupts log buffer. @@ -114,7 +115,7 @@ pub(crate) struct Gsp {/// Command queue. pub(crate) cmdq: Cmdq,/// RM arguments. - rmargs: CoherentAllocation<GspArgumentsPadded>, + rmargs: Coherent<GspArgumentsPadded>, }impl Gsp {@@ -123,34 +124,28 @@ pub(crate) fn new(pdev: &pci::Device<device::Bound>) -> impl PinInit<Self, Error pin_init::pin_init_scope (move || {let dev = pdev.as_ref (); +// Initialise the logging structures. The OpenRM equivalents are in: +// _kgspInitLibosLoggingStructures (allocates memory for buffers) +// kgspSetupLibosInitArgs_IMPL (creates pLibosInitArgs[] array) Ok (try_pin_init! (Self { - libos:CoherentAllocation ::<LibosMemoryRegionInitArgument >::alloc_coherent ( - dev, -GSP_PAGE_SIZE /size_of ::<LibosMemoryRegionInitArgument >(), -GFP_KERNEL | __GFP_ZERO, - )?, loginit:LogBuffer ::new (dev)?, logintr:LogBuffer ::new (dev)?, logrm:LogBuffer ::new (dev)?, cmdq:Cmdq ::new (dev)?, - rmargs:CoherentAllocation ::<GspArgumentsPadded >::alloc_coherent ( - dev, -1 , -GFP_KERNEL | __GFP_ZERO, - )?, - _: { -// Initialise the logging structures. The OpenRM equivalents are in: -// _kgspInitLibosLoggingStructures (allocates memory for buffers) -// kgspSetupLibosInitArgs_IMPL (creates pLibosInitArgs[] array) -dma_write! ( - libos, [0 ]?,LibosMemoryRegionInitArgument ::new ("LOGINIT" , &loginit.0 ) - ); -dma_write! ( - libos, [1 ]?,LibosMemoryRegionInitArgument ::new ("LOGINTR" , &logintr.0 ) - ); -dma_write! (libos, [2 ]?,LibosMemoryRegionInitArgument ::new ("LOGRM" , &logrm.0 )); -dma_write! (rmargs, [0 ]?.inner, fw::GspArgumentsCached ::new (cmdq)); -dma_write! (libos, [3 ]?,LibosMemoryRegionInitArgument ::new ("RMARGS" , rmargs)); + rmargs:Coherent ::init (dev,GFP_KERNEL ,GspArgumentsPadded ::new (cmdq))?, + libos: { +let mut libos =CoherentInit ::zeroed_slice ( + dev, +GSP_PAGE_SIZE /size_of ::<LibosMemoryRegionInitArgument >(), +GFP_KERNEL , + )?; + + libos.init_at (0 ,LibosMemoryRegionInitArgument ::new ("LOGINIT" , &loginit.0 ))?; + libos.init_at (1 ,LibosMemoryRegionInitArgument ::new ("LOGINTR" , &logintr.0 ))?; + libos.init_at (2 ,LibosMemoryRegionInitArgument ::new ("LOGRM" , &logrm.0 ))?; + libos.init_at (3 ,LibosMemoryRegionInitArgument ::new ("RMARGS" , rmargs))?; + + libos.into () }, })) })drivers/gpu/nova-core/gsp/fw.rs +3
-2@@ -9,11 +9,12 @@use core::ops::Range ;use kernel::{ - dma::CoherentAllocation , + dma::Coherent , prelude::*, ptr::{Alignable , -Alignment ,// +Alignment , +KnownSize ,// }, sizes::{SZ_128K ,
drivers/gpu/nova-core/gsp/fw.rs unsafe impl AsBytes for RunCpuSequencer {} · line 574
Quoted 7 lines
drivers/gpu/nova-core/gsp/fw.rs +3
-1@@ -568,7 +569,9 @@ unsafe impl AsBytes for RunCpuSequencer {}/// The memory allocated for the arguments must remain until the GSP sends the /// init_done RPC. #[repr(transparent)] -pub (crate )struct LibosMemoryRegionInitArgument (bindings::LibosMemoryRegionInitArgument ); +pub (crate )struct LibosMemoryRegionInitArgument { + inner: bindings::LibosMemoryRegionInitArgument , +}
FYI tuple struct construction is being worked at now:
https://github.com/Rust-for-Linux/pin-init/pull/113
Quoted 46 lines
drivers/gpu/nova-core/gsp/fw.rs +11
-6// SAFETY: Padding is explicit and does not contain uninitialized data. unsafe impl AsBytes for LibosMemoryRegionInitArgument {}@@ -578,10 +581,10 @@ unsafe impl AsBytes for LibosMemoryRegionInitArgument {}unsafe impl FromBytes for LibosMemoryRegionInitArgument {}impl LibosMemoryRegionInitArgument { -pub (crate )fn new <A :AsBytes +FromBytes >( +pub (crate )fn new <'a,A :AsBytes +FromBytes +KnownSize + ?Sized >( name: &'staticstr , - obj: &CoherentAllocation <A >, - ) ->Self { + obj: &'aCoherent <A >, + ) ->impl Init <Self > + 'a {/// Generates the `ID8` identifier required for some GSP objects. fn id8 (name: &str ) ->u64 {let mut bytes = [0u8 ; core::mem::size_of ::<u64 >()];@@ -593,7 +596,8 @@ fn id8(name: &str) -> u64 { u64::from_ne_bytes (bytes) } -Self (bindings::LibosMemoryRegionInitArgument { +#[allow(non_snake_case)] + let init_inner = init!(bindings::LibosMemoryRegionInitArgument { id8: id8(name), pa: obj.dma_handle(), size: num::usize_as_u64(obj.size()),@@ -603,7 +607,11 @@ fn id8(name: &str) -> u64 { loc: num::u32_into_u8::< { bindings::LibosMemoryRegionLoc_LIBOS_MEMORY_REGION_LOC_SYSMEM }, >(), - ..Default ::default () + ..Zeroable ::init_zeroed () + }); + +init! (LibosMemoryRegionInitArgument { + inner <- init_inner, }) } }@@ -814,15 +822,23 @@ unsafe impl FromBytes for GspMsgElement {}/// Arguments for GSP startup. #[repr(transparent)] -pub (crate )struct GspArgumentsCached (bindings::GSP_ARGUMENTS_CACHED ); +#[derive( Zeroable )]
drivers/gpu/nova-core/gsp/fw.rs unsafe impl FromBytes for GspMsgElement {} · line 832
Quoted 10 lines
drivers/gpu/nova-core/gsp/fw.rs +4
-3+pub (crate )struct GspArgumentsCached { + inner: bindings::GSP_ARGUMENTS_CACHED , +}impl GspArgumentsCached {/// Creates the arguments for starting the GSP up using `cmdq` as its command queue. -pub (crate )fn new (cmdq: &Cmdq ) ->Self { -Self (bindings::GSP_ARGUMENTS_CACHED { - messageQueueInitArguments:MessageQueueInitArguments ::new (cmdq).0 , +pub (crate )fn new (cmdq: &Cmdq ) ->impl Init <Self > + '_ {
This struct is not that big, so I think we can just keep the by-value constructor.
Best,
Gary
Quoted 59 lines
drivers/gpu/nova-core/gsp/fw.rs +23
-6+#[allow(non_snake_case)] +let init_inner =init! (bindings::GSP_ARGUMENTS_CACHED { + messageQueueInitArguments <-MessageQueueInitArguments ::new (cmdq), bDmemStack:1 , - ..Default ::default () + ..Zeroable ::init_zeroed () + }); + +init! (GspArgumentsCached { + inner <- init_inner, }) } }@@ -834,11 +850,21 @@ unsafe impl AsBytes for GspArgumentsCached {}/// must all be a multiple of GSP_PAGE_SIZE in size, so add padding to force it /// to that size. #[repr( C )] +#[derive( Zeroable )] pub (crate )struct GspArgumentsPadded {pub (crate ) inner:GspArgumentsCached , _padding: [u8 ;GSP_PAGE_SIZE - core::mem::size_of ::<bindings::GSP_ARGUMENTS_CACHED >()], } +impl GspArgumentsPadded { +pub (crate )fn new (cmdq: &Cmdq ) ->impl Init <Self > + '_ { +init! (GspArgumentsPadded { + inner <-GspArgumentsCached ::new (cmdq), + ..Zeroable ::init_zeroed () + }) + } +} +// SAFETY: Padding is explicit and will not contain uninitialized data. unsafe impl AsBytes for GspArgumentsPadded {}@@ -847,18 +873,18 @@ unsafe impl AsBytes for GspArgumentsPadded {}unsafe impl FromBytes for GspArgumentsPadded {}/// Init arguments for the message queue. -#[repr(transparent)] -struct MessageQueueInitArguments (bindings::MESSAGE_QUEUE_INIT_ARGUMENTS ); +type MessageQueueInitArguments = bindings::MESSAGE_QUEUE_INIT_ARGUMENTS ;impl MessageQueueInitArguments {/// Creates a new init arguments structure for `cmdq`. -fn new (cmdq: &Cmdq ) ->Self { -Self (bindings::MESSAGE_QUEUE_INIT_ARGUMENTS { +#[allow(non_snake_case)] +fn new (cmdq: &Cmdq ) ->impl Init <Self > + '_ { +init! (MessageQueueInitArguments { sharedMemPhysAddr: cmdq.dma_handle (), pageTableEntryCount: num::usize_into_u32 ::<{Cmdq ::NUM_PTES }>(), cmdQueueOffset: num::usize_as_u64 (Cmdq ::CMDQ_OFFSET ), statQueueOffset: num::usize_as_u64 (Cmdq ::STATQ_OFFSET ), - ..Default ::default () + ..Zeroable ::init_zeroed () }) } }
Danilo Krummrich
maintainerPATCH 8/8 gpu: nova-core: convert to new dma::Coherent API
In reply to Danilo KrummrichFrom: Gary Guo <[email protected]>
Remove all usages of dma::CoherentAllocation and use the new dma::Coherent type instead.
Note that there are still remainders of the old dma::CoherentAllocation API, such as as_slice() and as_slice_mut().
--- drivers/gpu/nova-core/dma.rs | 19 +++++------ drivers/gpu/nova-core/falcon.rs | 7 ++-- drivers/gpu/nova-core/firmware.rs | 10 ++---- drivers/gpu/nova-core/gsp.rs | 18 ++++++---- drivers/gpu/nova-core/gsp/cmdq.rs | 55 ++++++++++++------------------- 5 files changed, 46 insertions(+), 63 deletions(-)
drivers/gpu/nova-core/dma.rs +9 -10
@@ -9,13 +9,13 @@use kernel::{ device, - dma::CoherentAllocation , + dma::Coherent , page::PAGE_SIZE , prelude::*,// };pub (crate )struct DmaObject { - dma:CoherentAllocation <u8 >, + dma:Coherent <[u8 ]>, }impl DmaObject {
@@ -24,23 +24,22 @@ pub(crate) fn new(dev: &device::Device<device::Bound>, len: usize) -> Result<Sel .map_err(|_| EINVAL)? .pad_to_align () .size (); -let dma =CoherentAllocation ::alloc_coherent (dev, len,GFP_KERNEL | __GFP_ZERO)?; +let dma =Coherent ::zeroed_slice (dev, len,GFP_KERNEL )?;Ok (Self { dma }) }pub (crate )fn from_data (dev: &device::Device <device::Bound >, data: &[u8 ]) ->Result <Self > { -Self ::new (dev, data.len ()).and_then (|mut dma_obj| { -// SAFETY: We have just allocated the DMA memory, we are the only users and -// we haven't made the device aware of the handle yet. -unsafe { dma_obj.write (data,0 )? } -Ok (dma_obj) - }) +let dma_obj =Self ::new (dev, data.len ())?; +// SAFETY: We have just allocated the DMA memory, we are the only users and +// we haven't made the device aware of the handle yet. +unsafe { dma_obj.as_mut ()[..data.len ()].copy_from_slice (data) }; +Ok (dma_obj) } }impl Deref for DmaObject { -type Target =CoherentAllocation <u8 >; +type Target =Coherent <[u8 ]>;fn deref (&self) -> &Self ::Target { &self.dma
drivers/gpu/nova-core/falcon.rs +2 -5
@@ -25,10 +25,7 @@ driver::Bar0, falcon::hal::LoadMethod, gpu::Chipset, - num::{ - FromSafeCast, - IntoSafeCast, // - }, + num::FromSafeCast, regs, regs::macros::RegisterBase, // };
@@ -434,7 +431,7 @@ fn dma_wr<F: FalconFirmware<Target = E>>( } FalconMem::Dmem => (0 , - fw.dma_handle_with_offset (load_offsets.src_start.into_safe_cast ())?, + fw.dma_handle () +DmaAddress ::from (load_offsets.src_start), ), };if dma_start %DmaAddress ::from (DMA_LEN ) >0 {
drivers/gpu/nova-core/firmware.rs +3 -7
@@ -310,7 +310,7 @@ trait FirmwareSignature<F: FalconFirmware>: AsRef<[u8]> {}impl <F :FalconFirmware >FirmwareDmaObject <F ,Unsigned > {/// Patches the firmware at offset `sig_base_img` with `signature`. fn patch_signature <S :FirmwareSignature <F >>( -mut self, + self, signature: &S , sig_base_img:usize , ) ->Result <FirmwareDmaObject <F ,Signed >> {
@@ -320,12 +320,8 @@ fn patch_signature<S: FirmwareSignature<F>>( }// SAFETY: We are the only user of this object, so there cannot be any race. -let dst =unsafe { self.0 .start_ptr_mut ().add (sig_base_img) }; - -// SAFETY: `signature` and `dst` are valid, properly aligned, and do not overlap. -unsafe { - core::ptr::copy_nonoverlapping (signature_bytes.as_ptr (), dst, signature_bytes.len ()) - }; +let dst =unsafe { self.0 .as_mut () }; + dst[sig_base_img..][..signature_bytes.len ()].copy_from_slice (signature_bytes);Ok (FirmwareDmaObject (self.0 ,PhantomData )) }
drivers/gpu/nova-core/gsp.rs +11 -7
@@ -6,13 +6,15 @@ device, dma::{ Coherent, - CoherentAllocation, CoherentInit, DmaAddress, // }, pci, prelude::*, - transmute::AsBytes, // + transmute::{ +AsBytes , +FromBytes ,// + }, // };pub (crate )mod cmdq;
@@ -44,6 +46,9 @@#[repr( C )] struct PteArray <const NUM_ENTRIES :usize >([u64 ;NUM_ENTRIES ]); +/// SAFETY: arrays of `u64` implement `FromBytes` and we are but a wrapper around one. +unsafe impl <const NUM_ENTRIES :usize >FromBytes for PteArray <NUM_ENTRIES > {} +/// SAFETY: arrays of `u64` implement `AsBytes` and we are but a wrapper around one. unsafe impl <const NUM_ENTRIES :usize >AsBytes for PteArray <NUM_ENTRIES > {}
@@ -75,25 +80,24 @@ fn new(start: DmaAddress) -> Result<Self> {/// then pp points to index into the buffer where the next logging entry will /// be written. Therefore, the logging data is valid if: /// 1 <= pp < sizeof(buffer)/sizeof(u64) -struct LogBuffer (CoherentAllocation <u8 >); +struct LogBuffer (Coherent <[u8 ]>);impl LogBuffer {/// Creates a new `LogBuffer` mapped on `dev`. fn new (dev: &device::Device <device::Bound >) ->Result <Self > {const NUM_PAGES :usize =RM_LOG_BUFFER_NUM_PAGES ; -let mut obj =Self (CoherentAllocation ::<u8 >::alloc_coherent ( +let obj =Self (Coherent ::<u8 >::zeroed_slice ( dev,NUM_PAGES *GSP_PAGE_SIZE , -GFP_KERNEL | __GFP_ZERO, +GFP_KERNEL , )?);let ptes =PteArray ::<NUM_PAGES >::new (obj.0 .dma_handle ())?;// SAFETY: `obj` has just been created and we are its sole user. unsafe {// Copy the self-mapping PTE at the expected location. - obj.0 - .as_slice_mut (size_of ::<u64 >(),size_of_val (&ptes))? + obj.0 .as_mut ()[size_of ::<u64 >()..][..size_of_val (&ptes)] .copy_from_slice (ptes.as_bytes ()) };
drivers/gpu/nova-core/gsp/cmdq.rs +21 -34
143 lines not on this page · raw message
Signature · 1 line
2.53.0
Alexandre Courbot
maintainerRe: [PATCH 8/8] gpu: nova-core: convert to new dma::Coherent API
Quoted 26 lines · Danilo Krummrich
From: Gary Guo <[email protected]>
Remove all usages of
dma::CoherentAllocationand use the newdma::Coherenttype instead.Note that there are still remainders of the old
dma::CoherentAllocationAPI, such asas_slice()andas_slice_mut().Signed-off-by Gary Guo <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>--- drivers/gpu/nova-core/dma.rs | 19 +++++------ drivers/gpu/nova-core/falcon.rs | 7 ++-- drivers/gpu/nova-core/firmware.rs | 10 ++---- drivers/gpu/nova-core/gsp.rs | 18 ++++++---- drivers/gpu/nova-core/gsp/cmdq.rs | 55 ++++++++++++------------------- 5 files changed, 46 insertions(+), 63 deletions(-)drivers/gpu/nova-core/dma.rs +0
-0@@ -9,13 +9,13 @@use kernel::{ device,
drivers/gpu/nova-core/dma.rs line 19
Quoted 10 lines
drivers/gpu/nova-core/dma.rs +2
-2- dma::CoherentAllocation, + dma::Coherent, page::PAGE_SIZE, prelude::*, // };pub (crate )struct DmaObject { - dma:CoherentAllocation <u8 >, + dma:Coherent <[u8 ]>, }
Actually, do we even still have a need for DmaObject now that Coherent is available? It would be nice to check (as a follow-up patch, I can look into it) whether we can remove that whole nova-local dma module.
Quoted 50 lines
drivers/gpu/nova-core/dma.rs +7
-8impl DmaObject {@@ -24,23 +24,22 @@ pub(crate) fn new(dev: &device::Device<device::Bound>, len: usize) -> Result<Sel .map_err(|_| EINVAL)? .pad_to_align () .size (); -let dma =CoherentAllocation ::alloc_coherent (dev, len,GFP_KERNEL | __GFP_ZERO)?; +let dma =Coherent ::zeroed_slice (dev, len,GFP_KERNEL )?;Ok (Self { dma }) }pub (crate )fn from_data (dev: &device::Device <device::Bound >, data: &[u8 ]) ->Result <Self > { -Self ::new (dev, data.len ()).and_then (|mut dma_obj| { -// SAFETY: We have just allocated the DMA memory, we are the only users and -// we haven't made the device aware of the handle yet. -unsafe { dma_obj.write (data,0 )? } -Ok (dma_obj) - }) +let dma_obj =Self ::new (dev, data.len ())?; +// SAFETY: We have just allocated the DMA memory, we are the only users and +// we haven't made the device aware of the handle yet. +unsafe { dma_obj.as_mut ()[..data.len ()].copy_from_slice (data) }; +Ok (dma_obj) } }impl Deref for DmaObject { -type Target =CoherentAllocation <u8 >; +type Target =Coherent <[u8 ]>;fn deref (&self) -> &Self ::Target { &self.dmadrivers/gpu/nova-core/falcon.rs +1
-4@@ -25,10 +25,7 @@ driver::Bar0, falcon::hal::LoadMethod, gpu::Chipset, - num::{ - FromSafeCast, - IntoSafeCast, // - }, + num::FromSafeCast, regs, regs::macros::RegisterBase, // };
drivers/gpu/nova-core/falcon.rs fn dma_wr<F: FalconFirmware<Target = E>>( · line 434
Quoted 5 lines
drivers/gpu/nova-core/falcon.rs +1
-1@@ -434,7 +431,7 @@ fn dma_wr<F: FalconFirmware<Target = E>>( } FalconMem::Dmem => (0 , - fw.dma_handle_with_offset(load_offsets.src_start.into_safe_cast())?, + fw.dma_handle() + DmaAddress::from(load_offsets.src_start),
Aren't we losing the bounds checking done by dma_handle_with_offset?
Mmm, but looking below we are checking that the end of the transfer doesn't go beyond the object bounds, so that was probably redundant anyway. Maybe we should do a checked_add still for safety.
Gary Guo
reviewerRe: [PATCH 8/8] gpu: nova-core: convert to new dma::Coherent API
Quoted 101 lines · Alexandre Courbot
Quoted 26 lines · Danilo Krummrich
From: Gary Guo <[email protected]>
Remove all usages of
dma::CoherentAllocationand use the newdma::Coherenttype instead.Note that there are still remainders of the old
dma::CoherentAllocationAPI, such asas_slice()andas_slice_mut().Signed-off-by Gary Guo <[email protected]>Signed-off-by Danilo Krummrich <[email protected]>--- drivers/gpu/nova-core/dma.rs | 19 +++++------ drivers/gpu/nova-core/falcon.rs | 7 ++-- drivers/gpu/nova-core/firmware.rs | 10 ++---- drivers/gpu/nova-core/gsp.rs | 18 ++++++---- drivers/gpu/nova-core/gsp/cmdq.rs | 55 ++++++++++++------------------- 5 files changed, 46 insertions(+), 63 deletions(-)drivers/gpu/nova-core/dma.rs +0
-0@@ -9,13 +9,13 @@use kernel::{ device,drivers/gpu/nova-core/dma.rs line 19
Quoted 10 lines
drivers/gpu/nova-core/dma.rs +2
-2- dma::CoherentAllocation, + dma::Coherent, page::PAGE_SIZE, prelude::*, // };pub (crate )struct DmaObject { - dma:CoherentAllocation <u8 >, + dma:Coherent <[u8 ]>, }Actually, do we even still have a need for
DmaObjectnow thatCoherentis available? It would be nice to check (as a follow-up patch, I can look into it) whether we can remove that whole nova-localdmamodule.Quoted 50 lines
drivers/gpu/nova-core/dma.rs +7
-8impl DmaObject {@@ -24,23 +24,22 @@ pub(crate) fn new(dev: &device::Device<device::Bound>, len: usize) -> Result<Sel .map_err(|_| EINVAL)? .pad_to_align () .size (); -let dma =CoherentAllocation ::alloc_coherent (dev, len,GFP_KERNEL | __GFP_ZERO)?; +let dma =Coherent ::zeroed_slice (dev, len,GFP_KERNEL )?;Ok (Self { dma }) }pub (crate )fn from_data (dev: &device::Device <device::Bound >, data: &[u8 ]) ->Result <Self > { -Self ::new (dev, data.len ()).and_then (|mut dma_obj| { -// SAFETY: We have just allocated the DMA memory, we are the only users and -// we haven't made the device aware of the handle yet. -unsafe { dma_obj.write (data,0 )? } -Ok (dma_obj) - }) +let dma_obj =Self ::new (dev, data.len ())?; +// SAFETY: We have just allocated the DMA memory, we are the only users and +// we haven't made the device aware of the handle yet. +unsafe { dma_obj.as_mut ()[..data.len ()].copy_from_slice (data) }; +Ok (dma_obj) } }impl Deref for DmaObject { -type Target =CoherentAllocation <u8 >; +type Target =Coherent <[u8 ]>;fn deref (&self) -> &Self ::Target { &self.dmadrivers/gpu/nova-core/falcon.rs +1
-4@@ -25,10 +25,7 @@ driver::Bar0, falcon::hal::LoadMethod, gpu::Chipset, - num::{ - FromSafeCast, - IntoSafeCast, // - }, + num::FromSafeCast, regs, regs::macros::RegisterBase, // };drivers/gpu/nova-core/falcon.rs fn dma_wr<F: FalconFirmware<Target = E>>( · line 434
Quoted 5 lines
drivers/gpu/nova-core/falcon.rs +1
-1@@ -434,7 +431,7 @@ fn dma_wr<F: FalconFirmware<Target = E>>( } FalconMem::Dmem => (0 , - fw.dma_handle_with_offset(load_offsets.src_start.into_safe_cast())?, + fw.dma_handle() + DmaAddress::from(load_offsets.src_start),Aren't we losing the bounds checking done by
dma_handle_with_offset?
Quoted 3 lines
Mmm, but looking below we are checking that the end of the transfer doesn't go beyond the object bounds, so that was probably redundant anyway. Maybe we should do a
checked_addstill for safety.
I've had this as dma_handle_with_offset no longer make sense in the context of generic Coherent type. Although, I can probably add something like:
impl View<'_, Coherent<...>, ...> {
fn dma_handle(&self) -> DmaAddress;
}to replace this so you can get the DMA handle for any projections of the coherent object (and the bounds checking is done when projecting).
Best,
Gary
Andreas Hindborg
reviewerQuoted 36 lines · Danilo Krummrich
This patch series introduces the
dma::CoherentAPI Gary worked out in the context of his I/O projection work.Additionally, introduce
dma::CoherentInit, a type that encapsulates adma::Coherentobject before its DMA address is exposed to the device.dma::CoherentInitcan guarantee exclusive access to the innerdma::Coherentobject and implement Deref and DerefMut.Also add
Coherent::init()andCoherent::init_with_attrs()so we can directly initialize a newdma::Coherentobject through an impl Init<T, E>.Danilo Krummrich (5):
rust: dma: use "kernel vertical" style for imports
rust: dma: introducedma::CoherentInitfor memory initialization
rust: dma: add Coherent:init() andCoherent::init_with_attrs()
gpu: nova-core: useCoherent::initto initialize GspFwWprMeta
gpu: nova-core: convertGsp::new()to use CoherentInitGary Guo (3):
rust: dma: add generalized container for types other than slices
rust: dma: add zeroed constructor toCoherent
gpu: nova-core: convert to newdma::CoherentAPIdrivers/gpu/nova-core/dma.rs | 19 +- drivers/gpu/nova-core/falcon.rs | 7 +- drivers/gpu/nova-core/firmware.rs | 10 +- drivers/gpu/nova-core/gsp.rs | 65 ++-- drivers/gpu/nova-core/gsp/boot.rs | 7 +- drivers/gpu/nova-core/gsp/cmdq.rs | 55 +-- drivers/gpu/nova-core/gsp/fw.rs | 82 ++-- rust/kernel/device.rs | 4 +- rust/kernel/dma.rs | 626 +++++++++++++++++++++++------- samples/rust/rust_dma.rs | 8 +- 10 files changed, 619 insertions(+), 264 deletions(-)
Quoted 1 line
base-commit:
1195fcbda62f12108dc9be56fa4173897905b90c
What did you base this on?
Best regards,
Andreas Hindborg
Danilo Krummrich
maintainerQuoted 1 line · Andreas Hindborg
What did you base this on?
drm-rust-next
Andreas Hindborg
reviewerQuoted 4 lines · Danilo Krummrich
Quoted 1 line · Andreas Hindborg
What did you base this on?
drm-rust-next
I don't think 1195fcbda62f12108dc9be56fa4173897905b90c is in drm-rust-next - or any of the other branches in of
https://gitlab.freedesktop.org/drm/rust/kernel.git .
Best regards,
Andreas Hindborg
Danilo Krummrich
maintainerQuoted 10 lines · Andreas Hindborg
Quoted 4 lines · Danilo Krummrich
Quoted 1 line · Andreas Hindborg
What did you base this on?
drm-rust-next
I don't think
1195fcbda62f12108dc9be56fa4173897905b90cis in drm-rust-next - or any of the other branches in of
https://gitlab.freedesktop.org/drm/rust/kernel.git .
Oh, I did not notice that you replied to v1, there's already a v2.