I/O type generalization and projection
Subsystems (9)
cover I/O type generalization and projection
From: Gary Guo <[email protected]>
This series generalize Mmio/MmioRaw type from just an untyped region to typed representations (so MmioRaw<T> is __iomem *T). This allows us to remove the IoKnownSize trait; the information is sourced from just the pointer from the KnownSize trait instead.
This enables us to implement Io trait for Coherent<T>, enabling unified handling of MMIO and DMA coherent memory. It also paves the way to uniformly support shared system memory, which Tyr will likely need [1].
Built on this generalization, this series also add a io::View type which represents a subview of a bigger I/O region, and a io_project!() macro that provides a safe way to perform this. Some Nova code has been converted in this series to demonstrate cleanups possible with this addition.
This series depend on the Coherent API rework series [2].
Gary Guo (8):
rust: io: generalize MmioRaw to pointer to arbitrary type
rust: io: generalize Mmio to arbitrary type
rust: io: use pointer types instead of address
rust: io: add view type
rust: dma: add methods to unsafely create reference from subview
rust: io: add read_val and write_val function on I/O view
gpu: nova-core: use I/O projection for cleaner encapsulation
rust: dma: drop dma_read! and dma_write! API
drivers/gpu/nova-core/gsp.rs | 42 ++- drivers/gpu/nova-core/gsp/cmdq.rs | 69 +++-- drivers/gpu/nova-core/gsp/fw.rs | 84 ++--- rust/kernel/devres.rs | 11 +- rust/kernel/dma.rs | 217 ++++++------- rust/kernel/io.rs | 498 +++++++++++++++++++++++------- rust/kernel/io/mem.rs | 10 +- rust/kernel/io/poll.rs | 6 +- rust/kernel/io/register.rs | 19 +- rust/kernel/pci/io.rs | 88 ++++-- rust/kernel/ptr.rs | 7 + samples/rust/rust_dma.rs | 21 +- 12 files changed, 681 insertions(+), 391 deletions(-)
base-commit: 785f0eb2f85decbe7c1ef9ae922931f0194ffc2e
prerequisite-patch-id: 07a5643b01ce7f63ca42f1a322dcbdb5fc7fa9c2
prerequisite-patch-id: abae47bddac0d45e32dd54ce2f935b0675a6ebdf
prerequisite-patch-id: 7779e87914e4be91f0ced6760299ddf603943baf
prerequisite-patch-id: 31c43ae681611b92f24cbd369fac5af5834dd80f
prerequisite-patch-id: 60d56698d6bf30f31bed11375d5dc7eaeb359a0f
prerequisite-patch-id: 013e064c8c9dc0b7b0ff558ef0d9d6e674c629ee
prerequisite-patch-id: 5c5792a0435bdbdfd2aeb8a3d2dac79aa9ae7d6b
prerequisite-patch-id: 1e8d93ee75c56eecac13859c4024ea13f3cc872c
prerequisite-patch-id: b3a3589264ec10a5c33d4cea3ce69e9c6845d3dc
Signature · 1 line
2.51.2
PATCH 1/8 rust: io: generalize `MmioRaw` to pointer to arbitrary type
From: Gary Guo <[email protected]>
Conceptually, MmioRaw is just __iomem *, so it should work for any types. The existing use case where it represents a region of compile-time known minimum size and run-time known actual size is moved to a custom dynamic-sized type Region<SIZE> instead. The maxsize method is also renamed to size to reflect that it is the actual size (not a bound) of the region.
--- rust/kernel/devres.rs | 7 ++-- rust/kernel/io.rs | 84 +++++++++++++++++++++++++++++++++---------- rust/kernel/io/mem.rs | 4 +-- rust/kernel/pci/io.rs | 4 +-- 4 files changed, 74 insertions(+), 25 deletions(-)
rust/kernel/devres.rs +4 -3
@@ -71,14 +71,15 @@ struct Inner<T> {/// IoKnownSize, /// Mmio, /// MmioRaw, -/// PhysAddr, // +/// PhysAddr, +/// Region, // /// }, /// prelude::*, /// }; /// use core::ops::Deref; /// /// // See also [`pci::Bar`] for a real example. -/// struct IoMem<const SIZE: usize>(MmioRaw<SIZE>); +/// struct IoMem<const SIZE: usize>(MmioRaw<Region<SIZE>>); /// /// impl<const SIZE: usize> IoMem<SIZE> { /// /// # Safety
@@ -93,7 +94,7 @@ struct Inner<T> {/// return Err(ENOMEM); /// } /// -/// Ok(IoMem(MmioRaw::new(addr as usize, SIZE)?)) +/// Ok(IoMem(MmioRaw::new_region(addr as usize, SIZE)?)) /// } /// } ///
rust/kernel/io.rs +66 -18
152 lines not on this page · raw message
rust/kernel/io/mem.rs +2 -2
@@ -231,7 +231,7 @@ fn deref(&self) -> &Self::Target {/// [`IoMem`] always holds an [`MmioRaw`] instance that holds a valid pointer to the /// start of the I/O memory mapped region. pub struct IoMem <const SIZE :usize =0 > { - io:MmioRaw <SIZE >, + io:MmioRaw <super ::Region <SIZE >>, }impl <const SIZE :usize >IoMem <SIZE > {
@@ -266,7 +266,7 @@ fn ioremap(resource: &Resource) -> Result<Self> {return Err (ENOMEM ); } -let io =MmioRaw ::new (addras usize , size)?; +let io =MmioRaw ::new_region (addras usize , size)?;let io =IoMem { io };Ok (io)
rust/kernel/pci/io.rs +2 -2
@@ -148,7 +148,7 @@ impl<'a, S: ConfigSpaceKind> IoKnownSize for ConfigSpace<'a, S> {/// memory mapped PCI BAR and its size. pub struct Bar <const SIZE :usize =0 > { pdev:ARef <Device >, - io:MmioRaw <SIZE >, + io:MmioRaw <crate ::io::Region <SIZE >>, num:i32 , }
@@ -184,7 +184,7 @@ pub(super) fn new(pdev: &Device, num: u32, name: &CStr) -> Result<Self> {return Err (ENOMEM ); } -let io =match MmioRaw ::new (ioptr, lenas usize ) { +let io =match MmioRaw ::new_region (ioptr, lenas usize ) {Ok (io) => io,Err (err) => {// SAFETY:
Signature · 1 line
2.51.2
Andreas Hindborg
reviewerRe: [PATCH 1/8] rust: io: generalize `MmioRaw` to pointer to arbitrary type
Quoted 40 lines · Gary Guo
From: Gary Guo <[email protected]>
Conceptually,
MmioRawis just__iomem *, so it should work for any types. The existing use case where it represents a region of compile-time known minimum size and run-time known actual size is moved to a custom dynamic-sized typeRegion<SIZE>instead. Themaxsizemethod is also renamed tosizeto reflect that it is the actual size (not a bound) of the region.Signed-off-by Gary Guo <[email protected]>--- rust/kernel/devres.rs | 7 ++-- rust/kernel/io.rs | 84 +++++++++++++++++++++++++++++++++---------- rust/kernel/io/mem.rs | 4 +-- rust/kernel/pci/io.rs | 4 +-- 4 files changed, 74 insertions(+), 25 deletions(-)rust/kernel/devres.rs +3
-2@@ -71,14 +71,15 @@ struct Inner<T> {/// IoKnownSize, /// Mmio, /// MmioRaw, -/// PhysAddr, // +/// PhysAddr, +/// Region, // /// }, /// prelude::*, /// }; /// use core::ops::Deref; /// /// // See also [`pci::Bar`] for a real example. -/// struct IoMem<const SIZE: usize>(MmioRaw<SIZE>); +/// struct IoMem<const SIZE: usize>(MmioRaw<Region<SIZE>>); /// /// impl<const SIZE: usize> IoMem<SIZE> { /// /// # Safety
rust/kernel/devres.rs struct Inner<T> { · line 97
Quoted 5 lines
rust/kernel/devres.rs +1
-1@@ -93,7 +94,7 @@ struct Inner<T> {/// return Err(ENOMEM); /// } /// -/// Ok(IoMem(MmioRaw::new(addr as usize, SIZE)?)) +/// Ok(IoMem(MmioRaw::new_region(addr as usize, SIZE)?))
Should this be addr.addr() ?
Quoted 26 lines
rust/kernel/devres.rs +0
-0/// } /// } /// rust/kernel/io.rs +7
-1@@ -6,7 +6,8 @@use crate ::{ bindings, - prelude::*,// + prelude::*, + ptr::KnownSize ,// };pub mod mem;@@ -31,39 +32,85 @@/// `CONFIG_PHYS_ADDR_T_64BIT`, and it can be a u64 even on 32-bit architectures. pub type ResourceSize = bindings::resource_size_t ; +/// Untyped I/O region. +/// +/// This type can be used when an I/O region without known type information has a compile-time known +/// minimum size (and a runtime known actual size). +///
rust/kernel/io.rs line 49
Quoted 10 lines
rust/kernel/io.rs +10
-0+/// The `SIZE` generic parameter indicate the minimum size of the region. +#[repr(transparent)] +pub struct Region <const SIZE :usize =0 > { + inner: [u8 ], +} + +impl <const SIZE :usize >KnownSize for Region <SIZE > { +#[inline(always)] +fn size (p: *const Self ) ->usize { + (pas *const [u8 ]).len ()
Is as the only way to cast fat pointers?
Quoted 95 lines
rust/kernel/io.rs +45
-13+ } +} +/// Raw representation of an MMIO region. /// +/// `MmioRaw<T>` is equivalent to `T __iomem *` in C. +/// /// By itself, the existence of an instance of this structure does not provide any guarantees that /// the represented MMIO region does exist or is properly mapped. /// /// Instead, the bus specific MMIO implementation must convert this raw representation into an /// `Mmio` instance providing the actual memory accessors. Only by the conversion into an `Mmio` /// structure any guarantees are given. -pub struct MmioRaw <const SIZE :usize =0 > { - addr:usize , - maxsize:usize , +pub struct MmioRaw <T : ?Sized > { +/// Pointer is in I/O address space. +/// +/// The provenance does not matter, only the address and metadata do. + addr: *mut T , } -impl <const SIZE :usize >MmioRaw <SIZE > { -/// Returns a new `MmioRaw` instance on success, an error otherwise. -pub fn new (addr:usize , maxsize:usize ) ->Result <Self > { -if maxsize <SIZE { +// SAFETY: `MmioRaw` is just an address, so is thread-safe. +unsafe impl <T : ?Sized >Send for MmioRaw <T > {} +// SAFETY: `MmioRaw` is just an address, so is thread-safe. +unsafe impl <T : ?Sized >Sync for MmioRaw <T > {} + +impl <T >MmioRaw <T > { +/// Create a `MmioRaw` from address. +#[inline] +pub fn new (addr:usize ) ->Self { +Self { + addr: core::ptr::without_provenance_mut (addr), + } + } +} + +impl <const SIZE :usize >MmioRaw <Region <SIZE >> { +/// Create a `MmioRaw` representing a I/O region with given size. +/// +/// The size is checked against the minimum size specified via const generics. +#[inline] +pub fn new_region (addr:usize , size:usize ) ->Result <Self > { +if size <SIZE {return Err (EINVAL ); } -Ok (Self { addr, maxsize }) +let addr = core::ptr::slice_from_raw_parts_mut ::<u8 >( + core::ptr::without_provenance_mut (addr), + size, + )as *mut Region <SIZE >; +Ok (Self { addr }) } +} +impl <T : ?Sized +KnownSize >MmioRaw <T > {/// Returns the base address of the MMIO region. #[inline] pub fn addr (&self) ->usize { - self.addr + self.addr.addr () } -/// Returns the maximum size of the MMIO region. +/// Returns the size of the MMIO region. #[inline] -pub fn maxsize (&self) ->usize { - self.maxsize +pub fn size (&self) ->usize { +KnownSize ::size (self.addr) } }@@ -89,12 +136,13 @@ pub fn maxsize(&self) -> usize {/// Mmio, /// MmioRaw, /// PhysAddr, +/// Region, /// }, /// }; /// use core::ops::Deref; /// /// // See also `pci::Bar` for a real example. -/// struct IoMem<const SIZE: usize>(MmioRaw<SIZE>); +/// struct IoMem<const SIZE: usize>(MmioRaw<Region<SIZE>>); /// /// impl<const SIZE: usize> IoMem<SIZE> { /// /// # Safety
rust/kernel/io.rs pub fn maxsize(&self) -> usize { · line 160
Quoted 5 lines
rust/kernel/io.rs +1
-1@@ -109,7 +157,7 @@ pub fn maxsize(&self) -> usize {/// return Err(ENOMEM); /// } /// -/// Ok(IoMem(MmioRaw::new(addr as usize, SIZE)?)) +/// Ok(IoMem(MmioRaw::new_region(addr as usize, SIZE)?))
Should be addr.addr().
Quoted 44 lines
rust/kernel/io.rs +3
-3/// } /// } /// @@ -139,7 +187,7 @@ pub fn maxsize(&self) -> usize {/// # } /// ``` #[repr(transparent)] -pub struct Mmio <const SIZE :usize =0 >(MmioRaw <SIZE >); +pub struct Mmio <const SIZE :usize =0 >(MmioRaw <Region <SIZE >>);/// Checks whether an access of type `U` at the given `offset` /// is valid within this region. @@ -767,7 +815,7 @@ fn addr(&self) -> usize {/// Returns the maximum size of this mapping. #[inline] fn maxsize (&self) ->usize { - self.0 .maxsize () + self.0 .size () } }@@ -782,7 +830,7 @@ impl<const SIZE: usize> Mmio<SIZE> {/// /// Callers must ensure that `addr` is the start of a valid I/O mapped memory region of size /// `maxsize`. -pub unsafe fn from_raw (raw: &MmioRaw <SIZE >) -> &Self { +pub unsafe fn from_raw (raw: &MmioRaw <Region <SIZE >>) -> &Self {// SAFETY: `Mmio` is a transparent wrapper around `MmioRaw`. unsafe { &*core::ptr::from_ref (raw).cast () } }rust/kernel/io/mem.rs +1
-1@@ -231,7 +231,7 @@ fn deref(&self) -> &Self::Target {/// [`IoMem`] always holds an [`MmioRaw`] instance that holds a valid pointer to the /// start of the I/O memory mapped region. pub struct IoMem <const SIZE :usize =0 > { - io:MmioRaw <SIZE >, + io:MmioRaw <super ::Region <SIZE >>, }impl <const SIZE :usize >IoMem <SIZE > {
rust/kernel/io/mem.rs fn ioremap(resource: &Resource) -> Result<Self> { · line 269
Quoted 5 lines
rust/kernel/io/mem.rs +1
-1@@ -266,7 +266,7 @@ fn ioremap(resource: &Resource) -> Result<Self> {return Err (ENOMEM ); } -let io =MmioRaw ::new (addras usize , size)?; +let io =MmioRaw ::new_region (addras usize , size)?;
addr.addr()?
Quoted 17 lines
rust/kernel/io/mem.rs +0
-0let io =IoMem { io };Ok (io)rust/kernel/pci/io.rs +1
-1@@ -148,7 +148,7 @@ impl<'a, S: ConfigSpaceKind> IoKnownSize for ConfigSpace<'a, S> {/// memory mapped PCI BAR and its size. pub struct Bar <const SIZE :usize =0 > { pdev:ARef <Device >, - io:MmioRaw <SIZE >, + io:MmioRaw <crate ::io::Region <SIZE >>, num:i32 , }
rust/kernel/pci/io.rs pub(super) fn new(pdev: &Device, num: u32, name: &CStr) -> Result<Self> { · line 187
Quoted 5 lines
rust/kernel/pci/io.rs +1
-1@@ -184,7 +184,7 @@ pub(super) fn new(pdev: &Device, num: u32, name: &CStr) -> Result<Self> {return Err (ENOMEM ); } -let io =match MmioRaw ::new (ioptr, lenas usize ) { +let io =match MmioRaw ::new_region (ioptr, lenas usize ) {
Should this be len.try_into()??
Best regards,
Andreas Hindborg
Gary Guo
reviewerRe: [PATCH 1/8] rust: io: generalize `MmioRaw` to pointer to arbitrary type
Quoted 41 lines · Andreas Hindborg
Quoted 39 lines · Gary Guo
From: Gary Guo <[email protected]>
Conceptually,
MmioRawis just__iomem *, so it should work for any types. The existing use case where it represents a region of compile-time known minimum size and run-time known actual size is moved to a custom dynamic-sized typeRegion<SIZE>instead. Themaxsizemethod is also renamed tosizeto reflect that it is the actual size (not a bound) of the region.Signed-off-by Gary Guo <[email protected]>--- rust/kernel/devres.rs | 7 ++-- rust/kernel/io.rs | 84 +++++++++++++++++++++++++++++++++---------- rust/kernel/io/mem.rs | 4 +-- rust/kernel/pci/io.rs | 4 +-- 4 files changed, 74 insertions(+), 25 deletions(-)rust/kernel/devres.rs +3
-2@@ -71,14 +71,15 @@ struct Inner<T> {/// IoKnownSize, /// Mmio, /// MmioRaw, -/// PhysAddr, // +/// PhysAddr, +/// Region, // /// }, /// prelude::*, /// }; /// use core::ops::Deref; /// /// // See also [`pci::Bar`] for a real example. -/// struct IoMem<const SIZE: usize>(MmioRaw<SIZE>); +/// struct IoMem<const SIZE: usize>(MmioRaw<Region<SIZE>>); /// /// impl<const SIZE: usize> IoMem<SIZE> { /// /// # Safety
Quoted 8 lines
rust/kernel/devres.rs struct Inner<T> { · line 97
Quoted 6 lines
rust/kernel/devres.rs +1
-1@@ -93,7 +94,7 @@ struct Inner<T> {/// return Err(ENOMEM); /// } /// -/// Ok(IoMem(MmioRaw::new(addr as usize, SIZE)?)) +/// Ok(IoMem(MmioRaw::new_region(addr as usize, SIZE)?)) Should this be
addr.addr()?
This (and other occurence) are all existing use of casts introduced probably before we enabled strict provenance APIs. These should be fixed separately.
Quoted 31 lines
Quoted 31 lines
rust/kernel/devres.rs +0
-0/// } /// } /// rust/kernel/io.rs +11
-1@@ -6,7 +6,8 @@use crate ::{ bindings, - prelude::*,// + prelude::*, + ptr::KnownSize ,// };pub mod mem;@@ -31,39 +32,85 @@/// `CONFIG_PHYS_ADDR_T_64BIT`, and it can be a u64 even on 32-bit architectures. pub type ResourceSize = bindings::resource_size_t ; +/// Untyped I/O region. +/// +/// This type can be used when an I/O region without known type information has a compile-time known +/// minimum size (and a runtime known actual size). +/// +/// The `SIZE` generic parameter indicate the minimum size of the region. +#[repr(transparent)] +pub struct Region <const SIZE :usize =0 > { + inner: [u8 ],
Quoted 8 lines
rust/kernel/io.rs line 49
Quoted 6 lines
rust/kernel/io.rs +6
-0+} + +impl <const SIZE :usize >KnownSize for Region <SIZE > { +#[inline(always)] +fn size (p: *const Self ) ->usize { + (pas *const [u8 ]).len ()Is
asthe only way to cast fat pointers?
Yes. There's no way currently stable way to guarantee a matching metadata with traits.
Best,
Gary
Quoted 4 lines
Quoted 4 lines
rust/kernel/io.rs +3
-0+ } +} +
PATCH 2/8 rust: io: generalize `Mmio` to arbitrary type
In reply to Gary GuoFrom: Gary Guo <[email protected]>
Currently, io::Mmio always represent an untyped region of a compile-time known minimum size, which is roughly equivalent to void __iomem* (but with bound checks). However, it is useful to also be to represent I/O memory of a specific type, e.g. u32 __iomem* or struct foo __iomem*.
Thus, make Mmio generic on arbitrary T, where T is a sized type, or a DST that implements KnownSize. Similar to the MmioRaw change, the existing behaviour is preserved in the form of Mmio<Region<SIZE>>. This change brings the MMIO closer to the DMA coherent allocation types that we have, which is already typed.
To be able to implement IoKnownSize, add a MIN_SIZE constant to KnownSize trait to represent compile-time known minimum size of a specific type.
--- rust/kernel/devres.rs | 2 +- rust/kernel/io.rs | 63 ++++++++++++++++++++++---------------- rust/kernel/io/mem.rs | 4 +-- rust/kernel/io/poll.rs | 6 ++-- rust/kernel/io/register.rs | 19 +++++++----- rust/kernel/pci/io.rs | 2 +- rust/kernel/ptr.rs | 7 +++++ 7 files changed, 64 insertions(+), 39 deletions(-)
rust/kernel/devres.rs +1 -1
@@ -106,7 +106,7 @@ struct Inner<T> {/// } /// /// impl<const SIZE: usize> Deref for IoMem<SIZE> { -/// type Target = Mmio<SIZE>; +/// type Target = Mmio<Region<SIZE>>; /// /// fn deref(&self) -> &Self::Target { /// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`.
rust/kernel/io.rs +37 -26
207 lines not on this page · raw message
rust/kernel/io/mem.rs +2 -2
@@ -214,7 +214,7 @@ pub fn new<'a>(io_request: IoRequest<'a>) -> impl PinInit<Devres<Self>, Error> + }impl <const SIZE :usize >Deref for ExclusiveIoMem <SIZE > { -type Target =Mmio <SIZE >; +type Target =Mmio <super ::Region <SIZE >>;fn deref (&self) -> &Self ::Target { &self.iomem
@@ -289,7 +289,7 @@ fn drop(&mut self) { }impl <const SIZE :usize >Deref for IoMem <SIZE > { -type Target =Mmio <SIZE >; +type Target =Mmio <super ::Region <SIZE >>;fn deref (&self) -> &Self ::Target {// SAFETY: Safe as by the invariant of `IoMem`.
rust/kernel/io/poll.rs +4 -2
@@ -48,13 +48,14 @@/// use kernel::io::{ /// Io, /// Mmio, +/// Region, /// poll::read_poll_timeout, // /// }; /// use kernel::time::Delta; /// /// const HW_READY: u16 = 0x01; /// -/// fn wait_for_hardware<const SIZE: usize>(io: &Mmio<SIZE>) -> Result { +/// fn wait_for_hardware<const SIZE: usize>(io: &Mmio<Region<SIZE>>) -> Result { /// read_poll_timeout( /// // The `op` closure reads the value of a specific status register. /// || io.try_read16(0x1000),
@@ -135,13 +136,14 @@ pub fn read_poll_timeout<Op, Cond, T>(/// use kernel::io::{ /// Io, /// Mmio, +/// Region, /// poll::read_poll_timeout_atomic, // /// }; /// use kernel::time::Delta; /// /// const HW_READY: u16 = 0x01; /// -/// fn wait_for_hardware<const SIZE: usize>(io: &Mmio<SIZE>) -> Result { +/// fn wait_for_hardware<const SIZE: usize>(io: &Mmio<Region<SIZE>>) -> Result { /// read_poll_timeout_atomic( /// // The `op` closure reads the value of a specific status register. /// || io.try_read16(0x1000),
rust/kernel/io/register.rs +12 -7
@@ -55,6 +55,7 @@//! register, //! Io, //! IoLoc, +//! Region, //! }, //! num::Bounded, //! };
@@ -66,7 +67,7 @@//! # 3:0 minor_revision; //! # } //! # } -//! # fn test(io: &Mmio<0x1000>) { +//! # fn test(io: &Mmio<Region<0x1000>>) { //! # fn obtain_vendor_id() -> u8 { 0xff } //! //! // Read from the register's defined offset (0x100).
@@ -441,6 +442,7 @@ fn into_io_op(self) -> (FixedRegisterLoc<T>, T) {/// io::{ /// register, /// Io, +/// Region, /// }, /// }; /// # use kernel::io::Mmio;
@@ -452,7 +454,7 @@ fn into_io_op(self) -> (FixedRegisterLoc<T>, T) {/// } /// } /// -/// # fn test(io: &Mmio<0x1000>) { +/// # fn test(io: &Mmio<Region<0x1000>>) { /// let val = io.read(FIXED_REG); /// /// // Write from an already-existing value.
@@ -554,6 +556,7 @@ fn into_io_op(self) -> (FixedRegisterLoc<T>, T) {/// WithBase, /// }, /// Io, +/// Region, /// }, /// }; /// # use kernel::io::Mmio;
@@ -581,7 +584,7 @@ fn into_io_op(self) -> (FixedRegisterLoc<T>, T) {/// } /// } /// -/// # fn test(io: Mmio<0x1000>) { +/// # fn test(io: Mmio<Region<0x1000>>) { /// // Read the status of `Cpu0`. /// let cpu0_started = io.read(CPU_CTL::of::<Cpu0>()); ///
@@ -598,7 +601,7 @@ fn into_io_op(self) -> (FixedRegisterLoc<T>, T) {/// } /// } /// -/// # fn test2(io: Mmio<0x1000>) { +/// # fn test2(io: Mmio<Region<0x1000>>) { /// // Start the aliased `CPU0`, leaving its other fields untouched. /// io.update(CPU_CTL_ALIAS::of::<Cpu0>(), |r| r.with_alias_start(true)); /// # }
@@ -633,6 +636,7 @@ fn into_io_op(self) -> (FixedRegisterLoc<T>, T) {/// register, /// register::Array, /// Io, +/// Region, /// }, /// }; /// # use kernel::io::Mmio;
@@ -648,7 +652,7 @@ fn into_io_op(self) -> (FixedRegisterLoc<T>, T) {/// } /// } /// -/// # fn test(io: &Mmio<0x1000>) +/// # fn test(io: &Mmio<Region<0x1000>>) /// # -> Result<(), Error>{ /// // Read scratch register 0, i.e. I/O address `0x80`. /// let scratch_0 = io.read(SCRATCH::at(0)).value();
@@ -719,6 +723,7 @@ fn into_io_op(self) -> (FixedRegisterLoc<T>, T) {/// WithBase, /// }, /// Io, +/// Region, /// }, /// }; /// # use kernel::io::Mmio;
@@ -749,7 +754,7 @@ fn into_io_op(self) -> (FixedRegisterLoc<T>, T) {/// } /// } /// -/// # fn test(io: &Mmio<0x1000>) -> Result<(), Error> { +/// # fn test(io: &Mmio<Region<0x1000>>) -> Result<(), Error> { /// // Read scratch register 0 of CPU0. /// let scratch = io.read(CPU_SCRATCH::of::<Cpu0>().at(0)); ///
@@ -791,7 +796,7 @@ fn into_io_op(self) -> (FixedRegisterLoc<T>, T) {/// } /// } /// -/// # fn test2(io: &Mmio<0x1000>) -> Result<(), Error> { +/// # fn test2(io: &Mmio<Region<0x1000>>) -> Result<(), Error> { /// let cpu0_status = io.read(CPU_FIRMWARE_STATUS::of::<Cpu0>()).status(); /// # Ok(()) /// # }
rust/kernel/pci/io.rs +1 -1
@@ -238,7 +238,7 @@ fn drop(&mut self) { }impl <const SIZE :usize >Deref for Bar <SIZE > { -type Target =Mmio <SIZE >; +type Target =Mmio <crate ::io::Region <SIZE >>;fn deref (&self) -> &Self ::Target {// SAFETY: By the type invariant of `Self`, the MMIO range in `self.io` is properly mapped.
rust/kernel/ptr.rs +7 -0
@@ -236,11 +236,16 @@ fn align_up(self, alignment: Alignment) -> Option<Self> {/// /// This is a generalization of [`size_of`] that works for dynamically sized types. pub trait KnownSize { +/// Minimum size of this type known at compile-time. +const MIN_SIZE :usize ; +/// Get the size of an object of this type in bytes, with the metadata of the given pointer. fn size (p: *const Self ) ->usize ; }impl <T >KnownSize for T { +const MIN_SIZE :usize = core::mem::size_of ::<T >(); +#[inline(always)] fn size (_: *const Self ) ->usize {size_of ::<T >()
@@ -248,6 +253,8 @@ fn size(_: *const Self) -> usize { }impl <T >KnownSize for [T ] { +const MIN_SIZE :usize =0 ; +#[inline(always)] fn size (p: *const Self ) ->usize { p.len () *size_of ::<T >()
Signature · 1 line
2.51.2
Andreas Hindborg
reviewerRe: [PATCH 2/8] rust: io: generalize `Mmio` to arbitrary type
Quoted 64 lines · Gary Guo
From: Gary Guo <[email protected]>
Currently,
io::Mmioalways represent an untyped region of a compile-time known minimum size, which is roughly equivalent tovoid __iomem*(but with bound checks). However, it is useful to also be to represent I/O memory of a specific type, e.g.u32 __iomem*orstruct foo __iomem*.Thus, make
Mmiogeneric on arbitraryT, whereTis a sized type, or a DST that implementsKnownSize. Similar to theMmioRawchange, the existing behaviour is preserved in the form ofMmio<Region<SIZE>>. This change brings the MMIO closer to the DMA coherent allocation types that we have, which is already typed.To be able to implement
IoKnownSize, add aMIN_SIZEconstant toKnownSizetrait to represent compile-time known minimum size of a specific type.Signed-off-by Gary Guo <[email protected]>--- rust/kernel/devres.rs | 2 +- rust/kernel/io.rs | 63 ++++++++++++++++++++++---------------- rust/kernel/io/mem.rs | 4 +-- rust/kernel/io/poll.rs | 6 ++-- rust/kernel/io/register.rs | 19 +++++++----- rust/kernel/pci/io.rs | 2 +- rust/kernel/ptr.rs | 7 +++++ 7 files changed, 64 insertions(+), 39 deletions(-)rust/kernel/devres.rs +1
-1@@ -106,7 +106,7 @@ struct Inner<T> {/// } /// /// impl<const SIZE: usize> Deref for IoMem<SIZE> { -/// type Target = Mmio<SIZE>; +/// type Target = Mmio<Region<SIZE>>; /// /// fn deref(&self) -> &Self::Target { /// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`. rust/kernel/io.rs +3
-1@@ -44,6 +44,8 @@ pub struct Region<const SIZE: usize = 0> { }impl <const SIZE :usize >KnownSize for Region <SIZE > { +const MIN_SIZE :usize =SIZE ; +#[inline(always)] fn size (p: *const Self ) ->usize { (pas *const [u8 ]).len ()@@ -169,7 +171,7 @@ pub fn size(&self) -> usize {/// } /// /// impl<const SIZE: usize> Deref for IoMem<SIZE> { -/// type Target = Mmio<SIZE>; +/// type Target = Mmio<Region<SIZE>>; /// /// fn deref(&self) -> &Self::Target { /// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`.
rust/kernel/io.rs pub fn size(&self) -> usize { · line 192
Quoted 5 lines
rust/kernel/io.rs +1
-1@@ -187,7 +189,7 @@ pub fn size(&self) -> usize {/// # } /// ``` #[repr(transparent)] -pub struct Mmio <const SIZE :usize =0 >(MmioRaw <Region <SIZE >>); +pub struct Mmio <T : ?Sized >(MmioRaw <T >);
Why not have the KnownSize bound here? I think that would be more clear.
Best regards,
Andreas Hindborg
Gary Guo
reviewerRe: [PATCH 2/8] rust: io: generalize `Mmio` to arbitrary type
Quoted 65 lines · Andreas Hindborg
Quoted 63 lines · Gary Guo
From: Gary Guo <[email protected]>
Currently,
io::Mmioalways represent an untyped region of a compile-time known minimum size, which is roughly equivalent tovoid __iomem*(but with bound checks). However, it is useful to also be to represent I/O memory of a specific type, e.g.u32 __iomem*orstruct foo __iomem*.Thus, make
Mmiogeneric on arbitraryT, whereTis a sized type, or a DST that implementsKnownSize. Similar to theMmioRawchange, the existing behaviour is preserved in the form ofMmio<Region<SIZE>>. This change brings the MMIO closer to the DMA coherent allocation types that we have, which is already typed.To be able to implement
IoKnownSize, add aMIN_SIZEconstant toKnownSizetrait to represent compile-time known minimum size of a specific type.Signed-off-by Gary Guo <[email protected]>--- rust/kernel/devres.rs | 2 +- rust/kernel/io.rs | 63 ++++++++++++++++++++++---------------- rust/kernel/io/mem.rs | 4 +-- rust/kernel/io/poll.rs | 6 ++-- rust/kernel/io/register.rs | 19 +++++++----- rust/kernel/pci/io.rs | 2 +- rust/kernel/ptr.rs | 7 +++++ 7 files changed, 64 insertions(+), 39 deletions(-)rust/kernel/devres.rs +1
-1@@ -106,7 +106,7 @@ struct Inner<T> {/// } /// /// impl<const SIZE: usize> Deref for IoMem<SIZE> { -/// type Target = Mmio<SIZE>; +/// type Target = Mmio<Region<SIZE>>; /// /// fn deref(&self) -> &Self::Target { /// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`. rust/kernel/io.rs +3
-1@@ -44,6 +44,8 @@ pub struct Region<const SIZE: usize = 0> { }impl <const SIZE :usize >KnownSize for Region <SIZE > { +const MIN_SIZE :usize =SIZE ; +#[inline(always)] fn size (p: *const Self ) ->usize { (pas *const [u8 ]).len ()@@ -169,7 +171,7 @@ pub fn size(&self) -> usize {/// } /// /// impl<const SIZE: usize> Deref for IoMem<SIZE> { -/// type Target = Mmio<SIZE>; +/// type Target = Mmio<Region<SIZE>>; /// /// fn deref(&self) -> &Self::Target { /// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`.
Quoted 9 lines
rust/kernel/io.rs pub fn size(&self) -> usize { · line 192
Quoted 6 lines
rust/kernel/io.rs +1
-1@@ -187,7 +189,7 @@ pub fn size(&self) -> usize {/// # } /// ``` #[repr(transparent)] -pub struct Mmio <const SIZE :usize =0 >(MmioRaw <Region <SIZE >>); +pub struct Mmio <T : ?Sized >(MmioRaw <T >);Why not have the
KnownSizebound here? I think that would be more clear.
There's no need to put bounds on structs unless you need them for Drop or use of assoc types.
Best,
Gary
Quoted 3 lines
Best regards,
Andreas Hindborg
Andreas Hindborg
reviewerRe: [PATCH 2/8] rust: io: generalize `Mmio` to arbitrary type
Quoted 76 lines · Gary Guo
Quoted 65 lines · Andreas Hindborg
Quoted 63 lines · Gary Guo
From: Gary Guo <[email protected]>
Currently,
io::Mmioalways represent an untyped region of a compile-time known minimum size, which is roughly equivalent tovoid __iomem*(but with bound checks). However, it is useful to also be to represent I/O memory of a specific type, e.g.u32 __iomem*orstruct foo __iomem*.Thus, make
Mmiogeneric on arbitraryT, whereTis a sized type, or a DST that implementsKnownSize. Similar to theMmioRawchange, the existing behaviour is preserved in the form ofMmio<Region<SIZE>>. This change brings the MMIO closer to the DMA coherent allocation types that we have, which is already typed.To be able to implement
IoKnownSize, add aMIN_SIZEconstant toKnownSizetrait to represent compile-time known minimum size of a specific type.Signed-off-by Gary Guo <[email protected]>--- rust/kernel/devres.rs | 2 +- rust/kernel/io.rs | 63 ++++++++++++++++++++++---------------- rust/kernel/io/mem.rs | 4 +-- rust/kernel/io/poll.rs | 6 ++-- rust/kernel/io/register.rs | 19 +++++++----- rust/kernel/pci/io.rs | 2 +- rust/kernel/ptr.rs | 7 +++++ 7 files changed, 64 insertions(+), 39 deletions(-)rust/kernel/devres.rs +1
-1@@ -106,7 +106,7 @@ struct Inner<T> {/// } /// /// impl<const SIZE: usize> Deref for IoMem<SIZE> { -/// type Target = Mmio<SIZE>; +/// type Target = Mmio<Region<SIZE>>; /// /// fn deref(&self) -> &Self::Target { /// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`. rust/kernel/io.rs +3
-1@@ -44,6 +44,8 @@ pub struct Region<const SIZE: usize = 0> { }impl <const SIZE :usize >KnownSize for Region <SIZE > { +const MIN_SIZE :usize =SIZE ; +#[inline(always)] fn size (p: *const Self ) ->usize { (pas *const [u8 ]).len ()@@ -169,7 +171,7 @@ pub fn size(&self) -> usize {/// } /// /// impl<const SIZE: usize> Deref for IoMem<SIZE> { -/// type Target = Mmio<SIZE>; +/// type Target = Mmio<Region<SIZE>>; /// /// fn deref(&self) -> &Self::Target { /// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`. Quoted 9 lines
rust/kernel/io.rs pub fn size(&self) -> usize { · line 192
Quoted 6 lines
rust/kernel/io.rs +1
-1@@ -187,7 +189,7 @@ pub fn size(&self) -> usize {/// # } /// ``` #[repr(transparent)] -pub struct Mmio <const SIZE :usize =0 >(MmioRaw <Region <SIZE >>); +pub struct Mmio <T : ?Sized >(MmioRaw <T >);Why not have the
KnownSizebound here? I think that would be more clear.
Quoted 2 lines
There's no need to put bounds on structs unless you need them for
Dropor use of assoc types.
I understand there is no technical need, but it would help communicating how the code is intended to work. Unless I am mistaken, T will always be KnownSize, right?
Best regards,
Andreas Hindborg
Gary Guo
reviewerRe: [PATCH 2/8] rust: io: generalize `Mmio` to arbitrary type
Quoted 78 lines · Andreas Hindborg
Quoted 76 lines · Gary Guo
Quoted 74 lines · Andreas Hindborg
Quoted 64 lines · Gary Guo
From: Gary Guo <[email protected]>
Currently,
io::Mmioalways represent an untyped region of a compile-time known minimum size, which is roughly equivalent tovoid __iomem*(but with bound checks). However, it is useful to also be to represent I/O memory of a specific type, e.g.u32 __iomem*orstruct foo __iomem*.Thus, make
Mmiogeneric on arbitraryT, whereTis a sized type, or a DST that implementsKnownSize. Similar to theMmioRawchange, the existing behaviour is preserved in the form ofMmio<Region<SIZE>>. This change brings the MMIO closer to the DMA coherent allocation types that we have, which is already typed.To be able to implement
IoKnownSize, add aMIN_SIZEconstant toKnownSizetrait to represent compile-time known minimum size of a specific type.Signed-off-by Gary Guo <[email protected]>--- rust/kernel/devres.rs | 2 +- rust/kernel/io.rs | 63 ++++++++++++++++++++++---------------- rust/kernel/io/mem.rs | 4 +-- rust/kernel/io/poll.rs | 6 ++-- rust/kernel/io/register.rs | 19 +++++++----- rust/kernel/pci/io.rs | 2 +- rust/kernel/ptr.rs | 7 +++++ 7 files changed, 64 insertions(+), 39 deletions(-)rust/kernel/devres.rs +1
-1@@ -106,7 +106,7 @@ struct Inner<T> {/// } /// /// impl<const SIZE: usize> Deref for IoMem<SIZE> { -/// type Target = Mmio<SIZE>; +/// type Target = Mmio<Region<SIZE>>; /// /// fn deref(&self) -> &Self::Target { /// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`. rust/kernel/io.rs +3
-1@@ -44,6 +44,8 @@ pub struct Region<const SIZE: usize = 0> { }impl <const SIZE :usize >KnownSize for Region <SIZE > { +const MIN_SIZE :usize =SIZE ; +#[inline(always)] fn size (p: *const Self ) ->usize { (pas *const [u8 ]).len ()@@ -169,7 +171,7 @@ pub fn size(&self) -> usize {/// } /// /// impl<const SIZE: usize> Deref for IoMem<SIZE> { -/// type Target = Mmio<SIZE>; +/// type Target = Mmio<Region<SIZE>>; /// /// fn deref(&self) -> &Self::Target { /// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`. rust/kernel/io.rs pub fn size(&self) -> usize { · line 192
Quoted 5 lines
rust/kernel/io.rs +1
-1@@ -187,7 +189,7 @@ pub fn size(&self) -> usize {/// # } /// ``` #[repr(transparent)] -pub struct Mmio <const SIZE :usize =0 >(MmioRaw <Region <SIZE >>); +pub struct Mmio <T : ?Sized >(MmioRaw <T >);Why not have the
KnownSizebound here? I think that would be more clear.
Quoted 6 lines
Quoted 2 lines
There's no need to put bounds on structs unless you need them for
Dropor use of assoc types.I understand there is no technical need, but it would help communicating how the code is intended to work. Unless I am mistaken, T will always be
KnownSize, right?
I think most users don't need to know about this. All T: Sized will be `T:
KnownSize`, so if you're using it with a concrete type then the bound is already satisfied.
The same argument can be said to document
struct Coherent<T: AsBytes + FromBytes + KnownSize + ?Sized>
instead of just
struct Coherent<T: ?Sized + KnownSize>
// ^ In this case the drop does need KnownSize bound
But this just makes code more verbose as now you need to carry ?Sized bound everywhere.
If there's nothing other than documentation purpose I'd prefer to just leave it out.
Best,
Gary
Quoted 4 lines
Best regards,
Andreas Hindborg
Re: [PATCH 2/8] rust: io: generalize `Mmio` to arbitrary type
In reply to Gary GuoQuoted 14 lines · Gary Guo
From: Gary Guo <[email protected]>
Currently,
io::Mmioalways represent an untyped region of a compile-time known minimum size, which is roughly equivalent tovoid __iomem*(but with bound checks). However, it is useful to also be to represent I/O memory of a specific type, e.g.u32 __iomem*orstruct foo __iomem*.Thus, make
Mmiogeneric on arbitraryT, whereTis a sized type, or a DST that implementsKnownSize. Similar to theMmioRawchange, the existing behaviour is preserved in the form ofMmio<Region<SIZE>>. This change brings the MMIO closer to the DMA coherent allocation types that we have, which is already typed.
Quoted 5 lines
To be able to implement
IoKnownSize, add aMIN_SIZEconstant toKnownSizetrait to represent compile-time known minimum size of a specific type.Signed-off-by Gary Guo <[email protected]>
Cheers,
Miguel
Alexandre Courbot
maintainerRe: [PATCH 2/8] rust: io: generalize `Mmio` to arbitrary type
In reply to Gary GuoQuoted 7 lines · Gary Guo
From: Gary Guo <[email protected]>
Currently,
io::Mmioalways represent an untyped region of a compile-time known minimum size, which is roughly equivalent tovoid __iomem*(but with bound checks). However, it is useful to also be to represent I/O memory of a specific type, e.g.u32 __iomem*orstruct foo __iomem*.
Quoted 5 lines
Thus, make
Mmiogeneric on arbitraryT, whereTis a sized type, or a DST that implementsKnownSize. Similar to theMmioRawchange, the existing behaviour is preserved in the form ofMmio<Region<SIZE>>. This change brings the MMIO closer to the DMA coherent allocation types that we have, which is already typed.
You probably noticed, but the regular read8, read16 remain available irrespective of the T parameter, allowing the Mmio to be accessed using both the structured type and arbitrary primitives with an offset. I cannot find a reason to label this as unsound, but it might be confusing as it makes projection an additional capability on top of the existing raw I/O methods. This might be worth mentioning in the documentation, or maybe the primitive accessors should only be made available to Io<Region>?
Quoted 61 lines
To be able to implement
IoKnownSize, add aMIN_SIZEconstant toKnownSizetrait to represent compile-time known minimum size of a specific type.Signed-off-by Gary Guo <[email protected]>--- rust/kernel/devres.rs | 2 +- rust/kernel/io.rs | 63 ++++++++++++++++++++++---------------- rust/kernel/io/mem.rs | 4 +-- rust/kernel/io/poll.rs | 6 ++-- rust/kernel/io/register.rs | 19 +++++++----- rust/kernel/pci/io.rs | 2 +- rust/kernel/ptr.rs | 7 +++++ 7 files changed, 64 insertions(+), 39 deletions(-)rust/kernel/devres.rs +1
-1@@ -106,7 +106,7 @@ struct Inner<T> {/// } /// /// impl<const SIZE: usize> Deref for IoMem<SIZE> { -/// type Target = Mmio<SIZE>; +/// type Target = Mmio<Region<SIZE>>; /// /// fn deref(&self) -> &Self::Target { /// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`. rust/kernel/io.rs +4
-2@@ -44,6 +44,8 @@ pub struct Region<const SIZE: usize = 0> { }impl <const SIZE :usize >KnownSize for Region <SIZE > { +const MIN_SIZE :usize =SIZE ; +#[inline(always)] fn size (p: *const Self ) ->usize { (pas *const [u8 ]).len ()@@ -169,7 +171,7 @@ pub fn size(&self) -> usize {/// } /// /// impl<const SIZE: usize> Deref for IoMem<SIZE> { -/// type Target = Mmio<SIZE>; +/// type Target = Mmio<Region<SIZE>>; /// /// fn deref(&self) -> &Self::Target { /// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`. @@ -187,7 +189,7 @@ pub fn size(&self) -> usize {/// # } /// ``` #[repr(transparent)] -pub struct Mmio <const SIZE :usize =0 >(MmioRaw <Region <SIZE >>); +pub struct Mmio <T : ?Sized >(MmioRaw <T >);/// Checks whether an access of type `U` at the given `offset` /// is valid within this region.
rust/kernel/io.rs fn write64(&self, value: u64, offset: usize) · line 470
Quoted 8 lines
rust/kernel/io.rs +2
-1@@ -462,9 +464,10 @@ fn write64(&self, value: u64, offset: usize)/// use kernel::io::{ /// Io, /// Mmio, +/// Region, /// }; /// -/// fn do_reads(io: &Mmio) -> Result { +/// fn do_reads(io: &Mmio<Region<0>>) -> Result {
This can be &Mmio<Region>, and probably should be as it is closer to the original code which also used a size of 0 by default (applies to the other examples as well).
<snip>
rust/kernel/io.rs fn maxsize(&self) -> usize { · line 842
Quoted 10 lines
rust/kernel/io.rs +1
-1-impl <const SIZE :usize >Mmio <SIZE > { +impl <T : ?Sized +KnownSize >Mmio <T > {/// Converts an `MmioRaw` into an `Mmio` instance, providing the accessors to the MMIO mapping. /// /// # Safety /// /// Callers must ensure that `addr` is the start of a valid I/O mapped memory region of sizerust/kernel/io.rs +1
-2-/// `maxsize`. -pub unsafe fn from_raw (raw: &MmioRaw <Region <SIZE >>) -> &Self { +/// `addr.size()`.
That probably shouldn't be fixed by this patch, but there are is addr parameter for this method.
Gary Guo
reviewerRe: [PATCH 2/8] rust: io: generalize `Mmio` to arbitrary type
Quoted 14 lines · Alexandre Courbot
Quoted 7 lines · Gary Guo
From: Gary Guo <[email protected]>
Currently,
io::Mmioalways represent an untyped region of a compile-time known minimum size, which is roughly equivalent tovoid __iomem*(but with bound checks). However, it is useful to also be to represent I/O memory of a specific type, e.g.u32 __iomem*orstruct foo __iomem*.Quoted 5 lines
Thus, make
Mmiogeneric on arbitraryT, whereTis a sized type, or a DST that implementsKnownSize. Similar to theMmioRawchange, the existing behaviour is preserved in the form ofMmio<Region<SIZE>>. This change brings the MMIO closer to the DMA coherent allocation types that we have, which is already typed.
Quoted 8 lines
You probably noticed, but the regular
read8,read16remain available irrespective of theTparameter, allowing theMmioto be accessed using both the structured type and arbitrary primitives with an offset. I cannot find a reason to label this as unsound, but it might be confusing as it makes projection an additional capability on top of the existing raw I/O methods. This might be worth mentioning in the documentation, or maybe the primitive accessors should only be made available toIo<Region>?
Perhaps I could add a new UntypedIo trait which is implemented on Region? And I can restrict these methods to be only usable for it.
I would actually prefer to just remove them, and say you should either access via projections, or via register macro.
Best,
Gary
Quoted 5 lines
Quoted 5 lines
To be able to implement
IoKnownSize, add aMIN_SIZEconstant toKnownSizetrait to represent compile-time known minimum size of a specific type.
Alexandre Courbot
maintainerRe: [PATCH 2/8] rust: io: generalize `Mmio` to arbitrary type
Quoted 24 lines · Gary Guo
Quoted 14 lines · Alexandre Courbot
Quoted 7 lines · Gary Guo
From: Gary Guo <[email protected]>
Currently,
io::Mmioalways represent an untyped region of a compile-time known minimum size, which is roughly equivalent tovoid __iomem*(but with bound checks). However, it is useful to also be to represent I/O memory of a specific type, e.g.u32 __iomem*orstruct foo __iomem*.Quoted 5 lines
Thus, make
Mmiogeneric on arbitraryT, whereTis a sized type, or a DST that implementsKnownSize. Similar to theMmioRawchange, the existing behaviour is preserved in the form ofMmio<Region<SIZE>>. This change brings the MMIO closer to the DMA coherent allocation types that we have, which is already typed.Quoted 8 lines
You probably noticed, but the regular
read8,read16remain available irrespective of theTparameter, allowing theMmioto be accessed using both the structured type and arbitrary primitives with an offset. I cannot find a reason to label this as unsound, but it might be confusing as it makes projection an additional capability on top of the existing raw I/O methods. This might be worth mentioning in the documentation, or maybe the primitive accessors should only be made available toIo<Region>?
Quoted 5 lines
Perhaps I could add a new
UntypedIotrait which is implemented onRegion? And I can restrict these methods to be only usable for it.I would actually prefer to just remove them, and say you should either access via projections, or via register macro.
I am pretty sure there would still be users for more C-like accessors over an Region - although we should discourage their use, removing them entirely seems a bit drastic to me.
How about an extension trait of Io for when Io::Type is a region? This makes the feature unavailable unless the trait is explicitly imported - just the right level of friction imho.
PATCH 3/8 rust: io: use pointer types instead of address
In reply to Gary GuoFrom: Gary Guo <[email protected]>
This carries the size information with the pointer type and metadata, makes it possible to use I/O projections and paves the way for IO view types.
With this change, minimum size information becomes available through types; so KnownSize::MIN_SIZE can be used and IoKnownSize trait is no longer necessary. The trait is kept for compatibility and can be removed when users stop using it for bounds.
PCI config space uses only offsets and not pointers like MMIO; for this null pointers (with proper size metadata) is used. This is okay as I/O trait impl and I/O projections can operate on invalid pointers, and for PCI config space we will only use address info and ignore the provenance.
The current safety comment on io_read/io_write does not cover the topic about alignment, although this is guaranteed by checks in Io. Add it so it can be relied on by implementor of IoCapable.
--- rust/kernel/devres.rs | 2 +- rust/kernel/io.rs | 129 ++++++++++++++++++------------------------ rust/kernel/io/mem.rs | 2 +- rust/kernel/pci/io.rs | 82 +++++++++++++++++---------- 4 files changed, 111 insertions(+), 104 deletions(-)
rust/kernel/devres.rs +1 -1
@@ -101,7 +101,7 @@ struct Inner<T> {/// impl<const SIZE: usize> Drop for IoMem<SIZE> { /// fn drop(&mut self) { /// // SAFETY: `self.0.addr()` is guaranteed to be properly mapped by `Self::new`. -/// unsafe { bindings::iounmap(self.0.addr() as *mut c_void); }; +/// unsafe { bindings::iounmap(self.0.as_ptr().cast()); }; /// } /// } ///
rust/kernel/io.rs +56 -73
278 lines not on this page · raw message
rust/kernel/io/mem.rs +1 -1
@@ -284,7 +284,7 @@ pub fn new<'a>(io_request: IoRequest<'a>) -> impl PinInit<Devres<Self>, Error> +impl <const SIZE :usize >Drop for IoMem <SIZE > {fn drop (&mut self) {// SAFETY: Safe as by the invariant of `Io`. -unsafe { bindings::iounmap (self.io.addr ()as *mut c_void ) } +unsafe { bindings::iounmap (self.io.as_ptr ().cast ()) } } }
rust/kernel/pci/io.rs +53 -29
142 lines not on this page · raw message
Signature · 1 line
2.51.2
Re: [PATCH 3/8] rust: io: use pointer types instead of address
Quoted 21 lines · Gary Guo
From: Gary Guo <[email protected]>
This carries the size information with the pointer type and metadata, makes it possible to use I/O projections and paves the way for IO view types.
With this change, minimum size information becomes available through types; so
KnownSize::MIN_SIZEcan be used andIoKnownSizetrait is no longer necessary. The trait is kept for compatibility and can be removed when users stop using it for bounds.PCI config space uses only offsets and not pointers like MMIO; for this null pointers (with proper size metadata) is used. This is okay as I/O trait impl and I/O projections can operate on invalid pointers, and for PCI config space we will only use address info and ignore the provenance.
The current safety comment on
io_read/io_writedoes not cover the topic about alignment, although this is guaranteed by checks inIo. Add it so it can be relied on by implementor ofIoCapable.Signed-off-by Gary Guo <[email protected]>---
<cut>
rust/kernel/io.rs fn update<T, L, F>(&self, location: L, f: F) · line 792
Quoted 11 lines
rust/kernel/io.rs +2
-1+impl <T :Io + ?Sized >IoKnownSize for T {}/// Implements [`IoCapable`] on `$mmio` for `$ty` using `$read_fn` and `$write_fn`. macro_rules! impl_mmio_io_capable { ($mmio:ident, $(#[$attr:meta])* $ty:ty, $read_fn:ident, $write_fn:ident) => { $(#[$attr] )*impl <T : ?Sized >IoCapable <$ty>for $mmio<T > { -unsafe fn io_read (&self, address:usize ) -> $ty { +unsafe fn io_read (&self, address: *mut $ty) -> $ty {// SAFETY: By the trait invariant `address` is a valid address for MMIO operations. unsafe { bindings::$read_fn(addressas *const c_void ) }
Should we change this to a cast()?
Side question: Can you explain a situation where IoLoc::offset is not identity?
Best regards,
Andreas Hindborg
Gary Guo
reviewerRe: [PATCH 3/8] rust: io: use pointer types instead of address
Quoted 38 lines · Andreas Hindborg
Quoted 21 lines · Gary Guo
From: Gary Guo <[email protected]>
This carries the size information with the pointer type and metadata, makes it possible to use I/O projections and paves the way for IO view types.
With this change, minimum size information becomes available through types; so
KnownSize::MIN_SIZEcan be used andIoKnownSizetrait is no longer necessary. The trait is kept for compatibility and can be removed when users stop using it for bounds.PCI config space uses only offsets and not pointers like MMIO; for this null pointers (with proper size metadata) is used. This is okay as I/O trait impl and I/O projections can operate on invalid pointers, and for PCI config space we will only use address info and ignore the provenance.
The current safety comment on
io_read/io_writedoes not cover the topic about alignment, although this is guaranteed by checks inIo. Add it so it can be relied on by implementor ofIoCapable.Signed-off-by Gary Guo <[email protected]>---
<cut>
rust/kernel/io.rs fn update<T, L, F>(&self, location: L, f: F) · line 792
Quoted 11 lines
rust/kernel/io.rs +2
-1+impl <T :Io + ?Sized >IoKnownSize for T {}/// Implements [`IoCapable`] on `$mmio` for `$ty` using `$read_fn` and `$write_fn`. macro_rules! impl_mmio_io_capable { ($mmio:ident, $(#[$attr:meta])* $ty:ty, $read_fn:ident, $write_fn:ident) => { $(#[$attr] )*impl <T : ?Sized >IoCapable <$ty>for $mmio<T > { -unsafe fn io_read (&self, address:usize ) -> $ty { +unsafe fn io_read (&self, address: *mut $ty) -> $ty {// SAFETY: By the trait invariant `address` is a valid address for MMIO operations. unsafe { bindings::$read_fn(addressas *const c_void ) }
Quoted 1 line
Should we change this to a
cast()?
This is a *mut T -> *const c_void cast which needs cast_const().cast::<c_void> which I think is less readable than just as.
It's also existing code that I haven't touched in this commit.
Quoted 4 lines
Reviewed-by Andreas Hindborg <[email protected]>Side question: Can you explain a situation where
IoLoc::offsetis not identity?
By identity, you mean the impl of IoLoc for usize? IoLoc is also implemented for registers generated by register!() macro.
Best,
Gary
Re: [PATCH 3/8] rust: io: use pointer types instead of address
Quoted 5 lines · Gary Guo
This is a
*mut T->*const c_voidcast which needscast_const().cast::<c_void>which I think is less readable than justas.It's also existing code that I haven't touched in this commit.
I agree it is usually best to change it independently.
In any case, regarding the suggestion, the latter form is more restricted, which is what we wanted when we enabled the Clippy lints, no? Cc'ing Tamir.
I agree it is definitely less readable when one is not accustomed to the cast methods (e.g. which one is supposed to be used for what etc.), i.e. as is just obvious. On the other hand, it also makes more explicit that we are doing a "bigger jump", i.e. both const and type, which is why as is "worse" in that it allows for more things to happen at once.
Cheers,
Miguel
Alexandre Courbot
maintainerRe: [PATCH 3/8] rust: io: use pointer types instead of address
In reply to Gary GuoQuoted 9 lines · Gary Guo
From: Gary Guo <[email protected]>
This carries the size information with the pointer type and metadata, makes it possible to use I/O projections and paves the way for IO view types.
With this change, minimum size information becomes available through types; so
KnownSize::MIN_SIZEcan be used andIoKnownSizetrait is no longer necessary. The trait is kept for compatibility and can be removed when users stop using it for bounds.
Do we have users of IoKnownSize that we need to keep it around? I rebased your series on top of drm-rust-next for review and was able to remove IoKnownSize entirely. If possible I'd suggest removing it early in a dedicated patch right after this one.
Quoted 9 lines
PCI config space uses only offsets and not pointers like MMIO; for this null pointers (with proper size metadata) is used. This is okay as I/O trait impl and I/O projections can operate on invalid pointers, and for PCI config space we will only use address info and ignore the provenance.
The current safety comment on
io_read/io_writedoes not cover the topic about alignment, although this is guaranteed by checks inIo. Add it so it can be relied on by implementor ofIoCapable.
This patch does quite a few things, is there room for splitting a bit more?
Danilo Krummrich
maintainerRe: [PATCH 3/8] rust: io: use pointer types instead of address
Quoted 1 line · Alexandre Courbot
Do we have users of
IoKnownSizethat we need to keep it around?
nova-core has been a user so far, and since the patch series targets the driver-core tree it must be considered.
Alexandre Courbot
maintainerRe: [PATCH 3/8] rust: io: use pointer types instead of address
Quoted 5 lines · Danilo Krummrich
Quoted 1 line · Alexandre Courbot
Do we have users of
IoKnownSizethat we need to keep it around?nova-core has been a user so far, and since the patch series targets the driver-core tree it must be considered.
Ah right, in the nova-local register macro. Makes sense then.
PATCH 4/8 rust: io: add view type
In reply to Gary GuoFrom: Gary Guo <[email protected]>
The view may be created statically via I/O projection using io_project!() macro to perform compile-time checks, or created by type-casting an existing view type with try_cast() function, where the size and alignment checks are performed at runtime.
--- rust/kernel/io.rs | 147 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 146 insertions(+), 1 deletion(-)
rust/kernel/io.rs +146 -1
@@ -7,7 +7,11 @@use crate ::{ bindings, prelude::*, - ptr::KnownSize ,// + ptr::KnownSize , + transmute::{ +AsBytes , +FromBytes ,// + },// };pub mod mem;
@@ -296,6 +300,13 @@ pub trait Io {/// Type of this I/O region. For untyped I/O regions, [`Region`] type can be used. type Type : ?Sized +KnownSize ; +/// Get a [`View`] covering the entire region. +#[inline] +fn as_view (&self) ->View <'_,Self ,Self ::Type > { +// SAFETY: Trivially satisfied. +unsafe {View ::new_unchecked (self, self.as_ptr ()) } + } +/// Returns the base pointer of this mapping. /// /// This is a pointer to capture metadata. The specific meaning of the pointer depends on
@@ -895,3 +906,137 @@ pub fn relaxed(&self) -> &RelaxedMmio<T> { readq_relaxed, writeq_relaxed ); + +/// A view into an I/O region. +/// +/// # Invariants +/// +/// - `ptr` is aligned for `T` +/// - `ptr` has same provenance as `io.as_ptr()` +/// - `ptr.byte_offset_from(io.as_ptr())` is between 0 to +/// `KnownSize::size(io.as_ptr()) - KnownSize::size(ptr)`. +/// +/// These invariants are trivially satisfied if the pointer is created via pointer projection. +pub struct View <'a,IO : ?Sized ,T : ?Sized > { + io: &'aIO , + ptr: *mut T , +} + +impl <'a,IO : ?Sized ,T : ?Sized >View <'a,IO ,T > { +// For `io_project!` macro use only. +#[doc(hidden)] +#[inline] +pub fn as_view (&self) ->Self { + *self + } + +/// Create a view of a provided I/O region. +/// +/// # Safety +/// +/// `ptr` must satisfy the invariants of the view type. +#[inline] +pub unsafe fn new_unchecked (io: &'aIO , ptr: *mut T ) ->Self { +// INVARIANT: Per function safety requirement. +Self { io, ptr } + } + +/// Obtain the underlying I/O region. +#[inline] +pub fn io (self) -> &'aIO { + self.io + } + +/// Obtain a pointer to the subview. +/// +/// The interpretation of the pointer depends on the underlying I/O region. +#[inline] +pub fn as_ptr (self) -> *mut T { + self.ptr + } +} + +impl <IO : ?Sized ,T : ?Sized >Clone for View <'_,IO ,T > { +#[inline] +fn clone (&self) ->Self { + *self + } +} + +impl <IO : ?Sized ,T : ?Sized >Copy for View <'_,IO ,T > {} + +impl <'a,IO : ?Sized ,T : ?Sized >View <'a,IO ,T > { +/// Try to convert this view into a different typed I/O view. +/// +/// The target type must be of same or smaller size to current type, and the current view must +/// be properly aligned for the target type. +#[inline] +pub fn try_cast <U >(self) ->Result <View <'a,IO ,U >> +where +T :KnownSize +FromBytes +AsBytes , +U :FromBytes +AsBytes , + { +if size_of ::<U >() >KnownSize ::size (self.ptr) { +return Err (EINVAL ); + } + +if self.ptr.addr () %align_of ::<U >() !=0 { +return Err (EINVAL ); + } + +// INVARIANT: We have checked bounds and alignment. +Ok (View { + io: self.io, + ptr: self.ptr.cast (), + }) + } +} + +/// Project an I/O type to a subview of it. +/// +/// The syntax is of form `io_project!(io, proj)` where `io` is an expression to a type that +/// implements [`Io`] and `proj` is a [projection specification](kernel::ptr::project!). +/// +/// In addition to projecting from [`Io`], you may also project from a [`View`] of an [`Io`]. +/// +/// # Examples +/// +/// ``` +/// use kernel::io::{ +/// io_project, +/// Mmio, +/// View, +/// }; +/// struct MyStruct { field: u32, } +/// +/// // SAFETY: All bit patterns are acceptable values for `MyStruct`. +/// unsafe impl kernel::transmute::FromBytes for MyStruct{}; +/// // SAFETY: Instances of `MyStruct` have no uninitialized portions. +/// unsafe impl kernel::transmute::AsBytes for MyStruct{}; +/// +/// # fn test(mmio: &Mmio<[MyStruct]>) -> Result { +/// // let mmio: Mmio<[MyStruct]>; +/// let field: View<'_, _, u32> = io_project!(mmio, [1]?.field); +/// let whole: View<'_, _, MyStruct> = io_project!(mmio, [2]?); +/// let nested: View<'_, Mmio<_>, u32> = io_project!(whole, .field); +/// # Ok::<(), Error>(()) } +#[macro_export] +#[doc(hidden)] +macro_rules! io_project { + ($io:expr, $($proj:tt)*) => {{ +// Bring `as_view` to scope. +use $crate::io::Io as _; + +// Convert IO to view for unified handling. +// This also takes advantage to deref coercion. +let view: $crate::io::View <'_,_ ,_ > = $io.as_view (); +let ptr = $crate::ptr::project!( +mut view.as_ptr (), $($proj)* + ); +// SAFETY: projection of a projection is still a valid projection. +unsafe { $crate::io::View ::new_unchecked (view.io (), ptr) } + }}; +} + +#[doc(inline)] +pub use crate ::io_project;
Signature · 1 line
2.51.2
Re: [PATCH 4/8] rust: io: add view type
Quoted 30 lines · Gary Guo
From: Gary Guo <[email protected]>
The view may be created statically via I/O projection using
io_project!()macro to perform compile-time checks, or created by type-casting an existing view type withtry_cast()function, where the size and alignment checks are performed at runtime.Signed-off-by Gary Guo <[email protected]>--- rust/kernel/io.rs | 147 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 146 insertions(+), 1 deletion(-)rust/kernel/io.rs +5
-1@@ -7,7 +7,11 @@use crate ::{ bindings, prelude::*, - ptr::KnownSize ,// + ptr::KnownSize , + transmute::{ +AsBytes , +FromBytes ,// + },// };pub mod mem;
rust/kernel/io.rs pub trait Io { · line 306
Quoted 7 lines
rust/kernel/io.rs +4
-0@@ -296,6 +300,13 @@ pub trait Io {/// Type of this I/O region. For untyped I/O regions, [`Region`] type can be used. type Type : ?Sized +KnownSize ; +/// Get a [`View`] covering the entire region. +#[inline] +fn as_view (&self) ->View <'_,Self ,Self ::Type > { +// SAFETY: Trivially satisfied.
What might be trivial to you is not necessarily obvious to others. Please explain why we are satisfying safety requirements.
Otherwise looks good, with the above fixed, please add:
Best regards,
Andreas Hindborg
Gary Guo
reviewerRe: [PATCH 4/8] rust: io: add view type
Quoted 35 lines · Andreas Hindborg
Quoted 33 lines · Gary Guo
From: Gary Guo <[email protected]>
The view may be created statically via I/O projection using
io_project!()macro to perform compile-time checks, or created by type-casting an existing view type withtry_cast()function, where the size and alignment checks are performed at runtime.Signed-off-by Gary Guo <[email protected]>--- rust/kernel/io.rs | 147 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 146 insertions(+), 1 deletion(-)rust/kernel/io.rs +5
-1@@ -7,7 +7,11 @@use crate ::{ bindings, prelude::*, - ptr::KnownSize ,// + ptr::KnownSize , + transmute::{ +AsBytes , +FromBytes ,// + },// };pub mod mem;@@ -296,6 +300,13 @@ pub trait Io {/// Type of this I/O region. For untyped I/O regions, [`Region`] type can be used. type Type : ?Sized +KnownSize ;
Quoted 7 lines
rust/kernel/io.rs pub trait Io { · line 306
Quoted 4 lines
rust/kernel/io.rs +4
-0+/// Get a [`View`] covering the entire region. +#[inline] +fn as_view (&self) ->View <'_,Self ,Self ::Type > { +// SAFETY: Trivially satisfied. What might be trivial to you is not necessarily obvious to others. Please explain why we are satisfying safety requirements.
This is what language model produces:
Analysis: Io::as_view()
fn as_view(&self) -> View<'_, Self, Self::Type> {
// SAFETY: Trivially satisfied
unsafe { View::new_unchecked(self, self.as_ptr()) }
}
The View invariants are:
1. ptr is aligned for T
2. ptr has same provenance as io.as_ptr()
3. ptr.byte_offset_from(io.as_ptr()) is between 0 to KnownSize::size(io.as_ptr()) - KnownSize::size(ptr)
For as_view():
- ptr = self.as_ptr() which is Self::Type
- Invariant 1: self.as_ptr() should be aligned for Self::Type - assumed true from the Io trait
- Invariant 2: Same pointer, same provenance - trivially true
- Invariant 3: ptr.byte_offset_from(io.as_ptr()) = 0, and we need 0 <= size_io - size_ptr which is 0 <= 0, true
The safety comment "Trivially satisfied" is correct.
I think the verbosity here is really because we have the safety requirement listed item by item, rather than just defining a new concept.
If we, for example, coin an idea of IO valid pointers, then we can just say the self.as_ptr() is trivially I/O valid.
Perhaps, for this case, we can use the "projection trivially satisfy the invariants" that I've already mentioned in the doc, and just write
// SAFETY: This is an empty projection, so it trivially satisfies the
// invariant.?
Best,
Gary
Quoted 7 lines
Otherwise looks good, with the above fixed, please add:
Reviewed-by Andreas Hindborg <[email protected]>Best regards,
Andreas Hindborg
PATCH 5/8 rust: dma: add methods to unsafely create reference from subview
In reply to Gary GuoFrom: Gary Guo <[email protected]>
Implement Io for Coherent, so now dma::Coherent can be used with I/O projections.
This allows the as_ref() and as_mut() API to be used in smaller region than the whole DMA allocation itself. For example, if a ring buffer is shared between GPU and CPU, users may now use the io_project! API to obtain a view of the buffer that is unified owned by the CPU and get a reference.
--- rust/kernel/dma.rs | 56 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+)
rust/kernel/dma.rs +56 -0
@@ -12,6 +12,10 @@ Core, // }, error::to_result, + io::{ + Io, + IoCapable, // + }, prelude::*, ptr::KnownSize, sync::aref::ARef,
@@ -864,6 +868,58 @@ fn drop(&mut self) {// can be sent to another thread. unsafe impl <T :KnownSize +Send + ?Sized >Send for Coherent <T > {} +impl <T : ?Sized +KnownSize >Io for Coherent <T > { +type Type =T ; + +#[inline] +fn as_ptr (&self) -> *mut Self ::Type { + self.as_mut_ptr () + } +} + +impl <'a,B : ?Sized +KnownSize ,T : ?Sized >crate ::io::View <'a,Coherent <B >,T > { +/// Returns a DMA handle which may be given to the device as the DMA address base of +/// the region. +#[inline] +pub fn dma_handle (&self) ->DmaAddress { +let base = self.io (); +let offset = self.as_ptr ().addr () - base.as_ptr ().addr (); + base.dma_handle () + offsetas DmaAddress + } + +/// Returns a reference to the data in the region. +/// +/// # Safety +/// +/// * Callers must ensure that the device does not read/write to/from memory while the returned +/// slice is live. +/// * Callers must ensure that this call does not race with a write to the same region while +/// the returned slice is live. +#[inline] +pub unsafe fn as_ref (self) -> &'aT { +let ptr = self.as_ptr (); +// SAFETY: pointer is aligned and valid per type invariant of `View`. Aliasing rule is +// satisfied per safety requirement. +unsafe { &*ptr } + } + +/// Returns a mutable reference to the data in the region. +/// +/// # Safety +/// +/// * Callers must ensure that the device does not read/write to/from memory while the returned +/// slice is live. +/// * Callers must ensure that this call does not race with a read or write to the same region +/// while the returned slice is live. +#[inline] +pub unsafe fn as_mut (self) -> &'amut T { +let ptr = self.as_ptr (); +// SAFETY: pointer is aligned and valid per type invariant of `View`. Aliasing rule is +// satisfied per safety requirement. +unsafe { &mut *ptr } + } +} +/// Reads a field of an item from an allocated region of structs. /// /// The syntax is of the form `kernel::dma_read!(dma, proj)` where `dma` is an expression evaluating
Signature · 1 line
2.51.2
Andreas Hindborg
reviewerRe: [PATCH 5/8] rust: dma: add methods to unsafely create reference from subview
Quoted 9 lines · Gary Guo
From: Gary Guo <[email protected]>
Implement
IoforCoherent, so nowdma::Coherentcan be used with I/O projections.This allows the
as_ref()andas_mut()API to be used in smaller region than the whole DMA allocation itself. For example, if a ring buffer is shared between GPU and CPU, users may now use theio_project!API to obtain a view of the buffer that is unified owned by the CPU and get a reference.
What do you mean by "unified owned by the CPU"?
Quoted 25 lines
Signed-off-by Gary Guo <[email protected]>--- rust/kernel/dma.rs | 56 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+)rust/kernel/dma.rs +4
-0@@ -12,6 +12,10 @@ Core, // }, error::to_result, + io::{ + Io, + IoCapable, // + }, prelude::*, ptr::KnownSize, sync::aref::ARef,@@ -864,6 +868,58 @@ fn drop(&mut self) {// can be sent to another thread. unsafe impl <T :KnownSize +Send + ?Sized >Send for Coherent <T > {}
rust/kernel/dma.rs fn drop(&mut self) { · line 880
Quoted 10 lines
rust/kernel/dma.rs +10
-0+impl <T : ?Sized +KnownSize >Io for Coherent <T > { +type Type =T ; + +#[inline] +fn as_ptr (&self) -> *mut Self ::Type { + self.as_mut_ptr () + } +} + +impl <'a,B : ?Sized +KnownSize ,T : ?Sized >crate ::io::View <'a,Coherent <B >,T > {
Will this break orphan rule when we split kernel crate? Or will you put io and dma together in some core crate?
rust/kernel/dma.rs fn drop(&mut self) { · line 887
Quoted 7 lines
rust/kernel/dma.rs +7
-0+/// Returns a DMA handle which may be given to the device as the DMA address base of +/// the region. +#[inline] +pub fn dma_handle (&self) ->DmaAddress { +let base = self.io (); +let offset = self.as_ptr ().addr () - base.as_ptr ().addr (); + base.dma_handle () + offsetas DmaAddress
Do we need a // CAST: annotation?
Best regards,
Andreas Hindborg
Gary Guo
reviewerRe: [PATCH 5/8] rust: dma: add methods to unsafely create reference from subview
Quoted 7 lines · Andreas Hindborg
Quoted 5 lines · Gary Guo
From: Gary Guo <[email protected]>
Implement
IoforCoherent, so nowdma::Coherentcan be used with I/O projections.
Quoted 6 lines
Quoted 4 lines
This allows the
as_ref()andas_mut()API to be used in smaller region than the whole DMA allocation itself. For example, if a ring buffer is shared between GPU and CPU, users may now use theio_project!API to obtain a view of the buffer that is unified owned by the CPU and get a reference.What do you mean by "unified owned by the CPU"?
Oops, this should be "uniquely owned".
Quoted 26 lines
Quoted 26 lines
Signed-off-by Gary Guo <[email protected]>--- rust/kernel/dma.rs | 56 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+)rust/kernel/dma.rs +4
-0@@ -12,6 +12,10 @@ Core, // }, error::to_result, + io::{ + Io, + IoCapable, // + }, prelude::*, ptr::KnownSize, sync::aref::ARef,@@ -864,6 +868,58 @@ fn drop(&mut self) {// can be sent to another thread. unsafe impl <T :KnownSize +Send + ?Sized >Send for Coherent <T > {}
Quoted 13 lines
rust/kernel/dma.rs fn drop(&mut self) { · line 880
Quoted 10 lines
rust/kernel/dma.rs +10
-0+impl <T : ?Sized +KnownSize >Io for Coherent <T > { +type Type =T ; + +#[inline] +fn as_ptr (&self) -> *mut Self ::Type { + self.as_mut_ptr () + } +} + +impl <'a,B : ?Sized +KnownSize ,T : ?Sized >crate ::io::View <'a,Coherent <B >,T > {Will this break orphan rule when we split kernel crate? Or will you put
ioanddmatogether in some core crate?
It will unless we mark View as fundamental. However, I expect IO and DMA be under the same crate.
Best,
Gary
Quoted 14 lines
rust/kernel/dma.rs fn drop(&mut self) { · line 887
Quoted 8 lines
rust/kernel/dma.rs +7
-0+/// Returns a DMA handle which may be given to the device as the DMA address base of +/// the region. +#[inline] +pub fn dma_handle (&self) ->DmaAddress { +let base = self.io (); +let offset = self.as_ptr ().addr () - base.as_ptr ().addr (); + base.dma_handle () + offsetas DmaAddress Do we need a // CAST: annotation?
Best regards,
Andreas Hindborg
PATCH 6/8 rust: io: add `read_val` and `write_val` function on I/O view
In reply to Gary GuoFrom: Gary Guo <[email protected]>
When a view is narrowed to just a primitive, these functions provide a way to access them using the IoCapable trait. This is used to provide io_read! and io_write! macros, which are generalized version of current dma_read! and dma_write! macro (that works on Coherent only, but not subview of them, or other I/O backends).
For DMA coherent objects, IoCapable is only implemented for atomically accessible primitives; this is because read_volatile/write_volatile can behave undesirably for aggregates; LLVM may turn them to multiple instructions to access parts and assemble, or could combine them to a single instruction.
The ability to read/write aggregates (when atomicity is of no concern), could be implemented with copying primitives (e.g. memcpy_{from,to}io) in the future.
--- rust/kernel/dma.rs | 40 +++++++++++++++++++ rust/kernel/io.rs | 95 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 135 insertions(+)
rust/kernel/dma.rs +40 -0
@@ -877,6 +877,46 @@ fn as_ptr(&self) -> *mut Self::Type { } } +/// Implements [`IoCapable`] on `Coherent` for `$ty` using `read_volatile` and `write_volatile`. +macro_rules! impl_coherent_io_capable { + ($(#[$attr:meta])* $ty:ty) => { + $(#[$attr] )* +impl <T : ?Sized +KnownSize >IoCapable <$ty>for Coherent <T > { +#[inline] +unsafe fn io_read (&self, address: *mut $ty) -> $ty { +// SAFETY: +// - By the safety precondition, the address is within bounds of the allocation and +// aligned. +// - Using read_volatile() here so that race with hardware is well-defined. +// - Using read_volatile() here is not sound if it races with other CPU per Rust +// rules, but this is allowed per LKMM. +unsafe { address.read_volatile () } + } + +#[inline] +unsafe fn io_write (&self, value: $ty, address: *mut $ty) { +// SAFETY: +// - By the safety precondition, the address is within bounds of the allocation and +// aligned. +// - Using write_volatile() here so that race with hardware is well-defined. +// - Using write_volatile() here is not sound if it races with other CPU per Rust +// rules, but this is allowed per LKMM. +unsafe { address.write_volatile (value) } + } + } + }; +} + +// DMA regions support atomic 8, 16, and 32-bit accesses. +impl_coherent_io_capable! (u8 ); +impl_coherent_io_capable! (u16 ); +impl_coherent_io_capable! (u32 ); +// DMA regions on 64-bit systems also support atomic 64-bit accesses. +impl_coherent_io_capable! ( +#[cfg( CONFIG_64BIT )] +u64 +); +impl <'a,B : ?Sized +KnownSize ,T : ?Sized >crate ::io::View <'a,Coherent <B >,T > {/// Returns a DMA handle which may be given to the device as the DMA address base of /// the region.
rust/kernel/io.rs +95 -0
104 lines not on this page · raw message
Signature · 1 line
2.51.2
Andreas Hindborg
reviewerRe: [PATCH 6/8] rust: io: add `read_val` and `write_val` function on I/O view
Quoted 35 lines · Gary Guo
From: Gary Guo <[email protected]>
When a view is narrowed to just a primitive, these functions provide a way to access them using the
IoCapabletrait. This is used to provideio_read!andio_write!macros, which are generalized version of currentdma_read!anddma_write!macro (that works onCoherentonly, but not subview of them, or other I/O backends).For DMA coherent objects,
IoCapableis only implemented for atomically accessible primitives; this is becauseread_volatile/write_volatilecan behave undesirably for aggregates; LLVM may turn them to multiple instructions to access parts and assemble, or could combine them to a single instruction.The ability to read/write aggregates (when atomicity is of no concern), could be implemented with copying primitives (e.g. memcpy_{from,to}io) in the future.
Signed-off-by Gary Guo <[email protected]>--- rust/kernel/dma.rs | 40 +++++++++++++++++++ rust/kernel/io.rs | 95 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 135 insertions(+)rust/kernel/dma.rs +3
-0@@ -877,6 +877,46 @@ fn as_ptr(&self) -> *mut Self::Type { } } +/// Implements [`IoCapable`] on `Coherent` for `$ty` using `read_volatile` and `write_volatile`. +macro_rules! impl_coherent_io_capable { + ($(#[$attr:meta])* $ty:ty) => {
rust/kernel/dma.rs fn as_ptr(&self) -> *mut Self::Type { · line 892
Quoted 10 lines
rust/kernel/dma.rs +10
-0+ $(#[$attr])* + impl<T: ?Sized + KnownSize> IoCapable<$ty> for Coherent<T> { + #[inline] + unsafe fn io_read(&self, address: *mut $ty) -> $ty { + // SAFETY: + // - By the safety precondition, the address is within bounds of the allocation and + // aligned. + // - Using read_volatile() here so that race with hardware is well-defined. + // - Using read_volatile() here is not sound if it races with other CPU per Rust + // rules, but this is allowed per LKMM.
You are not covering how we satisfy "Reading from src must produce a properly initialized value of type T." I assume you need a bound on T: FromBytes?
Best regards,
Andreas Hindborg
Gary Guo
reviewerRe: [PATCH 6/8] rust: io: add `read_val` and `write_val` function on I/O view
Quoted 34 lines · Andreas Hindborg
Quoted 32 lines · Gary Guo
From: Gary Guo <[email protected]>
When a view is narrowed to just a primitive, these functions provide a way to access them using the
IoCapabletrait. This is used to provideio_read!andio_write!macros, which are generalized version of currentdma_read!anddma_write!macro (that works onCoherentonly, but not subview of them, or other I/O backends).For DMA coherent objects,
IoCapableis only implemented for atomically accessible primitives; this is becauseread_volatile/write_volatilecan behave undesirably for aggregates; LLVM may turn them to multiple instructions to access parts and assemble, or could combine them to a single instruction.The ability to read/write aggregates (when atomicity is of no concern), could be implemented with copying primitives (e.g. memcpy_{from,to}io) in the future.
Signed-off-by Gary Guo <[email protected]>--- rust/kernel/dma.rs | 40 +++++++++++++++++++ rust/kernel/io.rs | 95 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 135 insertions(+)rust/kernel/dma.rs +0
-0@@ -877,6 +877,46 @@ fn as_ptr(&self) -> *mut Self::Type { } }
Quoted 16 lines
rust/kernel/dma.rs fn as_ptr(&self) -> *mut Self::Type { · line 892
Quoted 13 lines
rust/kernel/dma.rs +13
-0+/// Implements [`IoCapable`] on `Coherent` for `$ty` using `read_volatile` and `write_volatile`. +macro_rules! impl_coherent_io_capable { + ($(#[$attr:meta])* $ty:ty) => { + $(#[$attr] )* +impl <T : ?Sized +KnownSize >IoCapable <$ty>for Coherent <T > { +#[inline] +unsafe fn io_read (&self, address: *mut $ty) -> $ty { +// SAFETY: +// - By the safety precondition, the address is within bounds of the allocation and +// aligned. +// - Using read_volatile() here so that race with hardware is well-defined. +// - Using read_volatile() here is not sound if it races with other CPU per Rust +// rules, but this is allowed per LKMM. You are not covering how we satisfy "Reading from src must produce a properly initialized value of type T." I assume you need a bound on
T: FromBytes?
The macro is only used for primitives. I'll add a line explaining that next version.
Best,
Gary
PATCH 7/8 gpu: nova-core: use I/O projection for cleaner encapsulation
In reply to Gary GuoFrom: Gary Guo <[email protected]>
Use io_project! for PTE array and message queues to remove the break off encapsulation.
The remaining dma_read! and dma_write! is now only acting on primitives; thus replace by io_read! and io_write!.
--- drivers/gpu/nova-core/gsp.rs | 42 +++++++++------- drivers/gpu/nova-core/gsp/cmdq.rs | 69 ++++++++++++++----------- drivers/gpu/nova-core/gsp/fw.rs | 84 ++++++++++++------------------- 3 files changed, 96 insertions(+), 99 deletions(-)
drivers/gpu/nova-core/gsp.rs +25 -17
@@ -9,8 +9,13 @@ CoherentBox, DmaAddress, // }, + io::{ + self, + io_project, // + }, pci, prelude::*, + ptr::KnownSize, transmute::{AsBytes ,FromBytes ,//
@@ -53,12 +58,20 @@ unsafe impl<const NUM_ENTRIES: usize> FromBytes for PteArray<NUM_ENTRIES> {}unsafe impl <const NUM_ENTRIES :usize >AsBytes for PteArray <NUM_ENTRIES > {}impl <const NUM_PAGES :usize >PteArray <NUM_PAGES > { -/// Returns the page table entry for `index`, for a mapping starting at `start`. -// TODO: Replace with `IoView` projection once available. -fn entry (start:DmaAddress , index:usize ) ->Result <u64 > { - start - .checked_add (num::usize_as_u64 (index) <<GSP_PAGE_SHIFT ) - .ok_or (EOVERFLOW ) +/// Initialize a new page table array mapping `NUM_PAGES` GSP pages starting at address `start`. +fn init <T :FromBytes +AsBytes +KnownSize + ?Sized >( + view: io::View <'_,Coherent <T >,Self >, + start:DmaAddress , + ) ->Result <()> { +for iin 0 ..NUM_PAGES { +io_project! (view, .0 [i]).write_val ( + start + .checked_add (num::usize_as_u64 (i) <<GSP_PAGE_SHIFT ) + .ok_or (EOVERFLOW )?, + ); + } + +Ok (()) } }
@@ -90,17 +103,12 @@ fn new(dev: &device::Device<device::Bound>) -> Result<Self> { )?);let start_addr = obj.0 .dma_handle (); - -// SAFETY: `obj` has just been created and we are its sole user. -let pte_region = -unsafe { &mut obj.0 .as_mut ()[size_of ::<u64 >()..][..NUM_PAGES *size_of ::<u64 >()] }; - -// Write values one by one to avoid an on-stack instance of `PteArray`. -for (i, chunk)in pte_region.chunks_exact_mut (size_of ::<u64 >()).enumerate () { -let pte_value =PteArray ::<0 >::entry (start_addr, i)?; - - chunk.copy_from_slice (&pte_value.to_ne_bytes ()); - } +let pte_view =io_project! ( + obj.0 , + [size_of ::<u64 >()..]?[..NUM_PAGES *size_of ::<u64 >()]? + ) + .try_cast ::<PteArray <NUM_PAGES >>()?; +PteArray ::init (pte_view, start_addr)?;Ok (obj) }
drivers/gpu/nova-core/gsp/cmdq.rs +40 -29
147 lines not on this page · raw message
drivers/gpu/nova-core/gsp/fw.rs +31 -53
108 lines not on this page · raw message
Signature · 1 line
2.51.2
PATCH 8/8 rust: dma: drop `dma_read!` and `dma_write!` API
In reply to Gary GuoFrom: Gary Guo <[email protected]>
The primitive read/write use case is covered by the io_read! and io_write! macro. The non-primitive use case was finicky; they should either be achieved using CoherentBox or as_ref()/as_mut() to assert the lack of concurrent access, or should be using memcpy-like APIs to express the non-atomic and tearable nature.
--- rust/kernel/dma.rs | 131 --------------------------------------- samples/rust/rust_dma.rs | 21 ++++--- 2 files changed, 14 insertions(+), 138 deletions(-)
rust/kernel/dma.rs +0 -131
@@ -598,52 +598,6 @@ pub unsafe fn as_mut(&self) -> &mut T {// SAFETY: per safety requirement. unsafe { &mut *self.as_mut_ptr () } } - -/// Reads the value of `field` and ensures that its type is [`FromBytes`]. -/// -/// # Safety -/// -/// This must be called from the [`dma_read`] macro which ensures that the `field` pointer is -/// validated beforehand. -/// -/// Public but hidden since it should only be used from [`dma_read`] macro. -#[doc(hidden)] -pub unsafe fn field_read <F :FromBytes >(&self, field: *const F ) ->F { -// SAFETY: -// - By the safety requirements field is valid. -// - Using read_volatile() here is not sound as per the usual rules, the usage here is -// a special exception with the following notes in place. When dealing with a potential -// race from a hardware or code outside kernel (e.g. user-space program), we need that -// read on a valid memory is not UB. Currently read_volatile() is used for this, and the -// rationale behind is that it should generate the same code as READ_ONCE() which the -// kernel already relies on to avoid UB on data races. Note that the usage of -// read_volatile() is limited to this particular case, it cannot be used to prevent -// the UB caused by racing between two kernel functions nor do they provide atomicity. -unsafe { field.read_volatile () } - } - -/// Writes a value to `field` and ensures that its type is [`AsBytes`]. -/// -/// # Safety -/// -/// This must be called from the [`dma_write`] macro which ensures that the `field` pointer is -/// validated beforehand. -/// -/// Public but hidden since it should only be used from [`dma_write`] macro. -#[doc(hidden)] -pub unsafe fn field_write <F :AsBytes >(&self, field: *mut F , val:F ) { -// SAFETY: -// - By the safety requirements field is valid. -// - Using write_volatile() here is not sound as per the usual rules, the usage here is -// a special exception with the following notes in place. When dealing with a potential -// race from a hardware or code outside kernel (e.g. user-space program), we need that -// write on a valid memory is not UB. Currently write_volatile() is used for this, and the -// rationale behind is that it should generate the same code as WRITE_ONCE() which the -// kernel already relies on to avoid UB on data races. Note that the usage of -// write_volatile() is limited to this particular case, it cannot be used to prevent -// the UB caused by racing between two kernel functions nor do they provide atomicity. -unsafe { field.write_volatile (val) } - } }impl <T :AsBytes +FromBytes >Coherent <T > {
@@ -959,88 +913,3 @@ pub unsafe fn as_mut(self) -> &'a mut T {unsafe { &mut *ptr } } } - -/// Reads a field of an item from an allocated region of structs. -/// -/// The syntax is of the form `kernel::dma_read!(dma, proj)` where `dma` is an expression evaluating -/// to a [`Coherent`] and `proj` is a [projection specification](kernel::ptr::project!). -/// -/// # Examples -/// -/// ``` -/// use kernel::device::Device; -/// use kernel::dma::{attrs::*, Coherent}; -/// -/// struct MyStruct { field: u32, } -/// -/// // SAFETY: All bit patterns are acceptable values for `MyStruct`. -/// unsafe impl kernel::transmute::FromBytes for MyStruct{}; -/// // SAFETY: Instances of `MyStruct` have no uninitialized portions. -/// unsafe impl kernel::transmute::AsBytes for MyStruct{}; -/// -/// # fn test(alloc: &kernel::dma::Coherent<[MyStruct]>) -> Result { -/// let whole = kernel::dma_read!(alloc, [2]?); -/// let field = kernel::dma_read!(alloc, [1]?.field); -/// # Ok::<(), Error>(()) } -/// ``` -#[macro_export] -macro_rules! dma_read { - ($dma:expr, $($proj:tt)*) => {{ -let dma = &$dma; -let ptr = $crate::ptr::project!( - $crate ::dma::Coherent ::as_ptr (dma), $($proj)* - ); -// SAFETY: The pointer created by the projection is within the DMA region. -unsafe { $crate::dma::Coherent ::field_read (dma, ptr) } - }}; -} - -/// Writes to a field of an item from an allocated region of structs. -/// -/// The syntax is of the form `kernel::dma_write!(dma, proj, val)` where `dma` is an expression -/// evaluating to a [`Coherent`], `proj` is a -/// [projection specification](kernel::ptr::project!), and `val` is the value to be written to the -/// projected location. -/// -/// # Examples -/// -/// ``` -/// use kernel::device::Device; -/// use kernel::dma::{attrs::*, Coherent}; -/// -/// struct MyStruct { member: u32, } -/// -/// // SAFETY: All bit patterns are acceptable values for `MyStruct`. -/// unsafe impl kernel::transmute::FromBytes for MyStruct{}; -/// // SAFETY: Instances of `MyStruct` have no uninitialized portions. -/// unsafe impl kernel::transmute::AsBytes for MyStruct{}; -/// -/// # fn test(alloc: &kernel::dma::Coherent<[MyStruct]>) -> Result { -/// kernel::dma_write!(alloc, [2]?.member, 0xf); -/// kernel::dma_write!(alloc, [1]?, MyStruct { member: 0xf }); -/// # Ok::<(), Error>(()) } -/// ``` -#[macro_export] -macro_rules! dma_write { - (@parse [$dma:expr] [$($proj:tt)*] [, $val:expr]) => {{ -let dma = &$dma; -let ptr = $crate::ptr::project!( -mut $crate ::dma::Coherent ::as_mut_ptr (dma), $($proj)* - ); -let val = $val; -// SAFETY: The pointer created by the projection is within the DMA region. -unsafe { $crate::dma::Coherent ::field_write (dma, ptr, val) } - }}; - (@parse [$dma:expr] [$($proj:tt)*] [.$field:tt $($rest:tt)*]) => { - $crate::dma_write!(@parse [$dma] [$($proj)* .$field] [$($rest)*]) - }; - (@parse [$dma:expr] [$($proj:tt)*] [[$index:expr]? $($rest:tt)*]) => { - $crate::dma_write!(@parse [$dma] [$($proj)* [$index]?] [$($rest)*]) - }; - (@parse [$dma:expr] [$($proj:tt)*] [[$index:expr] $($rest:tt)*]) => { - $crate::dma_write!(@parse [$dma] [$($proj)* [$index]] [$($rest)*]) - }; - ($dma:expr, $($rest:tt)*) => { - $crate::dma_write!(@parse [$dma] [] [$($rest)*]) - }; -}
samples/rust/rust_dma.rs +14 -7
@@ -6,7 +6,14 @@use kernel::{ device::Core , - dma::{Coherent ,DataDirection ,Device ,DmaMask }, + dma::{ +Coherent , +CoherentBox , +DataDirection , +Device , +DmaMask ,// + }, + io::io_read, page, pci, prelude::*, scatterlist::{Owned ,SGTable },
@@ -64,11 +71,11 @@ 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:Coherent <[MyStruct ]> = -Coherent ::zeroed_slice (pdev.as_ref (),TEST_VALUES .len (),GFP_KERNEL )?; +let mut ca:CoherentBox <[MyStruct ]> = +CoherentBox ::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 )); + ca.init_at (i,MyStruct ::new (value.0 , value.1 ))?; }let size =4 * page::PAGE_SIZE ;
@@ -78,7 +85,7 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> impl PinInit<Self, EOk (try_pin_init! (Self { pdev: pdev.into (), - ca, + ca: ca.into (), sgt <- sgt, })) })
@@ -88,8 +95,8 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> impl PinInit<Self, Eimpl DmaSampleDriver {fn check_dma (&self) ->Result {for (i, value)in TEST_VALUES .into_iter ().enumerate () { -let val0 = kernel::dma_read!(self.ca, [i]?.h); -let val1 = kernel::dma_read!(self.ca, [i]?.b); +let val0 =io_read! (self.ca, [i]?.h); +let val1 =io_read! (self.ca, [i]?.b);assert_eq! (val0, value.0 );assert_eq! (val1, value.1 );
Signature · 1 line
2.51.2
Re: [PATCH 8/8] rust: dma: drop `dma_read!` and `dma_write!` API
Quoted 9 lines · Gary Guo
From: Gary Guo <[email protected]>
The primitive read/write use case is covered by the
io_read!andio_write!macro. The non-primitive use case was finicky; they should either be achieved usingCoherentBoxoras_ref()/as_mut()to assert the lack of concurrent access, or should be using memcpy-like APIs to express the non-atomic and tearable nature.Signed-off-by Gary Guo <[email protected]>
Best regards,
Andreas Hindborg
Andreas Hindborg
reviewerHi Gary,
Quoted 48 lines · Gary Guo
From: Gary Guo <[email protected]>
This series generalize
Mmio/MmioRawtype from just an untyped region to typed representations (soMmioRaw<T>is__iomem *T). This allows us to remove theIoKnownSizetrait; the information is sourced from just the pointer from theKnownSizetrait instead.This enables us to implement
Iotrait forCoherent<T>, enabling unified handling of MMIO and DMA coherent memory. It also paves the way to uniformly support shared system memory, which Tyr will likely need [1].Built on this generalization, this series also add a
io::Viewtype which represents a subview of a bigger I/O region, and aio_project!()macro that provides a safe way to perform this. Some Nova code has been converted in this series to demonstrate cleanups possible with this addition.This series depend on the Coherent API rework series [2].
Gary Guo (8):
rust: io: generalizeMmioRawto pointer to arbitrary type
rust: io: generalizeMmioto arbitrary type
rust: io: use pointer types instead of address
rust: io: add view type
rust: dma: add methods to unsafely create reference from subview
rust: io: addread_valandwrite_valfunction on I/O view
gpu: nova-core: use I/O projection for cleaner encapsulation
rust: dma: dropdma_read!anddma_write!APIdrivers/gpu/nova-core/gsp.rs | 42 ++- drivers/gpu/nova-core/gsp/cmdq.rs | 69 +++-- drivers/gpu/nova-core/gsp/fw.rs | 84 ++--- rust/kernel/devres.rs | 11 +- rust/kernel/dma.rs | 217 ++++++------- rust/kernel/io.rs | 498 +++++++++++++++++++++++------- rust/kernel/io/mem.rs | 10 +- rust/kernel/io/poll.rs | 6 +- rust/kernel/io/register.rs | 19 +- rust/kernel/pci/io.rs | 88 ++++-- rust/kernel/ptr.rs | 7 + samples/rust/rust_dma.rs | 21 +- 12 files changed, 681 insertions(+), 391 deletions(-)
Quoted 1 line
base-commit:
785f0eb2f85decbe7c1ef9ae922931f0194ffc2e
What did you base this on? I can't find this commit.
Best regards,
Andreas Hindborg
Quoted 2 lines · Andreas Hindborg
What did you base this on? I can't find this commit.
It is next-20260320.
Cheers,
Miguel
Alexandre Courbot
maintainerQuoted 18 lines · Gary Guo
From: Gary Guo <[email protected]>
This series generalize
Mmio/MmioRawtype from just an untyped region to typed representations (soMmioRaw<T>is__iomem *T). This allows us to remove theIoKnownSizetrait; the information is sourced from just the pointer from theKnownSizetrait instead.This enables us to implement
Iotrait forCoherent<T>, enabling unified handling of MMIO and DMA coherent memory. It also paves the way to uniformly support shared system memory, which Tyr will likely need [1].Built on this generalization, this series also add a
io::Viewtype which represents a subview of a bigger I/O region, and aio_project!()macro that provides a safe way to perform this. Some Nova code has been converted in this series to demonstrate cleanups possible with this addition.
Quoted 4 lines
This series depend on the Coherent API rework series [2].
I'm getting quite a few clippy warnings when applying this series:
warning: lint `clippy::invalid_null_ptr_usage` has been renamed to `invalid_null_arguments`
--> ../rust/kernel/pci/io.rs:78:9
|
78 | clippy::invalid_null_ptr_usage,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `invalid_null_arguments`
|
= note: `#[warn(renamed_and_removed_lints)]` on by default
warning: lint `clippy::invalid_null_ptr_usage` has been renamed to `invalid_null_arguments`
--> ../rust/kernel/pci/io.rs:94:9
|
94 | clippy::invalid_null_ptr_usage,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `invalid_null_arguments`
warning: macro has unnecessary safety comment
--> ../rust/kernel/io.rs:1045:1
|
1045 | macro_rules! io_project {
| ^^^^^^^^^^^^^^^^^^^^^^^^^
|
help: consider removing the safety comment
--> ../rust/kernel/io.rs:1034:8
|
1034 | /// // SAFETY: Instances of `MyStruct` have no uninitialized portions.
| ^^^^^^^
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.94.0/index.html#unnecessary_safety_comment
= note: requested on the command line with `-W clippy::unnecessary-safety-comment`
warning: macro has unnecessary safety comment
--> ../rust/kernel/io.rs:1086:1
|
1086 | macro_rules! io_read {
| ^^^^^^^^^^^^^^^^^^^^^^
|
help: consider removing the safety comment
--> ../rust/kernel/io.rs:1077:8
|
1077 | /// // SAFETY: Instances of `MyStruct` have no uninitialized portions.
| ^^^^^^^
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.94.0/index.html#unnecessary_safety_comment
warning: macro has unnecessary safety comment
--> ../rust/kernel/io.rs:1118:1
|
1118 | macro_rules! io_write {
| ^^^^^^^^^^^^^^^^^^^^^^^
|
help: consider removing the safety comment
--> ../rust/kernel/io.rs:1109:8
|
1109 | /// // SAFETY: Instances of `MyStruct` have no uninitialized portions.
| ^^^^^^^
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.94.0/index.html#unnecessary_safety_comment
warning: 5 warnings emittedGary Guo
reviewerQuoted 26 lines · Alexandre Courbot
Quoted 18 lines · Gary Guo
From: Gary Guo <[email protected]>
This series generalize
Mmio/MmioRawtype from just an untyped region to typed representations (soMmioRaw<T>is__iomem *T). This allows us to remove theIoKnownSizetrait; the information is sourced from just the pointer from theKnownSizetrait instead.This enables us to implement
Iotrait forCoherent<T>, enabling unified handling of MMIO and DMA coherent memory. It also paves the way to uniformly support shared system memory, which Tyr will likely need [1].Built on this generalization, this series also add a
io::Viewtype which represents a subview of a bigger I/O region, and aio_project!()macro that provides a safe way to perform this. Some Nova code has been converted in this series to demonstrate cleanups possible with this addition.Quoted 4 lines
This series depend on the Coherent API rework series [2].
I'm getting quite a few clippy warnings when applying this series:
Quoted 13 lines
warning: lint `clippy::invalid_null_ptr_usage` has been renamed to `invalid_null_arguments`
--> ../rust/kernel/pci/io.rs:78:9
|
78 | clippy::invalid_null_ptr_usage,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `invalid_null_arguments`
|
= note: `#[warn(renamed_and_removed_lints)]` on by default
warning: lint `clippy::invalid_null_ptr_usage` has been renamed to `invalid_null_arguments`
--> ../rust/kernel/pci/io.rs:94:9
|
94 | clippy::invalid_null_ptr_usage,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `invalid_null_arguments`Yeah, the lint was moved from clippy to rustc in later version of Rust (which doesn't have the false positive).
Good thing is that the false positive should be already fixed in Rust 1.85, so when I send a new version next cycle I should be able to just remove this allow.
Quoted 14 lines
warning: macro has unnecessary safety comment
--> ../rust/kernel/io.rs:1045:1
|
1045 | macro_rules! io_project {
| ^^^^^^^^^^^^^^^^^^^^^^^^^
|
help: consider removing the safety comment
--> ../rust/kernel/io.rs:1034:8
|
1034 | /// // SAFETY: Instances of `MyStruct` have no uninitialized portions.
| ^^^^^^^
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.94.0/index.html#unnecessary_safety_comment
= note: requested on the command line with `-W clippy::unnecessary-safety-comment`This looks like a new false positive to me. The code below it is unsafe impl.
Best,
Gary
Quoted 28 lines
warning: macro has unnecessary safety comment
--> ../rust/kernel/io.rs:1086:1
|
1086 | macro_rules! io_read {
| ^^^^^^^^^^^^^^^^^^^^^^
|
help: consider removing the safety comment
--> ../rust/kernel/io.rs:1077:8
|
1077 | /// // SAFETY: Instances of `MyStruct` have no uninitialized portions.
| ^^^^^^^
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.94.0/index.html#unnecessary_safety_comment
warning: macro has unnecessary safety comment
--> ../rust/kernel/io.rs:1118:1
|
1118 | macro_rules! io_write {
| ^^^^^^^^^^^^^^^^^^^^^^^
|
help: consider removing the safety comment
--> ../rust/kernel/io.rs:1109:8
|
1109 | /// // SAFETY: Instances of `MyStruct` have no uninitialized portions.
| ^^^^^^^
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.94.0/index.html#unnecessary_safety_comment
warning: 5 warnings emitted