// SPDX-License-Identifier: GPL-2.012//! Direct memory access (DMA).3//!4//! C header: [`include/linux/dma-mapping.h`](srctree/include/linux/dma-mapping.h)56use crate::{7bindings, build_assert, device,8device::{Bound, Core},9error::{to_result, Result},10prelude::*,11sync::aref::ARef,12transmute::{AsBytes, FromBytes},13};14use core::ptr::NonNull;1516/// DMA address type.17///18/// Represents a bus address used for Direct Memory Access (DMA) operations.19///20/// This is an alias of the kernel's `dma_addr_t`, which may be `u32` or `u64` depending on21/// `CONFIG_ARCH_DMA_ADDR_T_64BIT`.22///23/// Note that this may be `u64` even on 32-bit architectures.24pub type DmaAddress = bindings::dma_addr_t;2526/// Trait to be implemented by DMA capable bus devices.27///28/// The [`dma::Device`](Device) trait should be implemented by bus specific device representations,29/// where the underlying bus is DMA capable, such as:30#[cfg_attr(CONFIG_PCI, doc = "* [`pci::Device`](kernel::pci::Device)")]31/// * [`platform::Device`](::kernel::platform::Device)32pub trait Device: AsRef<device::Device<Core>> {33/// Set up the device's DMA streaming addressing capabilities.34///35/// This method is usually called once from `probe()` as soon as the device capabilities are36/// known.37///38/// # Safety39///40/// This method must not be called concurrently with any DMA allocation or mapping primitives,41/// such as [`CoherentAllocation::alloc_attrs`].42unsafe fn dma_set_mask(&self, mask: DmaMask) -> Result {43// SAFETY:44// - By the type invariant of `device::Device`, `self.as_ref().as_raw()` is valid.45// - The safety requirement of this function guarantees that there are no concurrent calls46// to DMA allocation and mapping primitives using this mask.47to_result(unsafe { bindings::dma_set_mask(self.as_ref().as_raw(), mask.value()) })48}4950/// Set up the device's DMA coherent addressing capabilities.51///52/// This method is usually called once from `probe()` as soon as the device capabilities are53/// known.54///55/// # Safety56///57/// This method must not be called concurrently with any DMA allocation or mapping primitives,58/// such as [`CoherentAllocation::alloc_attrs`].59unsafe fn dma_set_coherent_mask(&self, mask: DmaMask) -> Result {60// SAFETY:61// - By the type invariant of `device::Device`, `self.as_ref().as_raw()` is valid.62// - The safety requirement of this function guarantees that there are no concurrent calls63// to DMA allocation and mapping primitives using this mask.64to_result(unsafe { bindings::dma_set_coherent_mask(self.as_ref().as_raw(), mask.value()) })65}6667/// Set up the device's DMA addressing capabilities.68///69/// This is a combination of [`Device::dma_set_mask`] and [`Device::dma_set_coherent_mask`].70///71/// This method is usually called once from `probe()` as soon as the device capabilities are72/// known.73///74/// # Safety75///76/// This method must not be called concurrently with any DMA allocation or mapping primitives,77/// such as [`CoherentAllocation::alloc_attrs`].78unsafe fn dma_set_mask_and_coherent(&self, mask: DmaMask) -> Result {79// SAFETY:80// - By the type invariant of `device::Device`, `self.as_ref().as_raw()` is valid.81// - The safety requirement of this function guarantees that there are no concurrent calls82// to DMA allocation and mapping primitives using this mask.83to_result(unsafe {84bindings::dma_set_mask_and_coherent(self.as_ref().as_raw(), mask.value())85})86}87}8889/// A DMA mask that holds a bitmask with the lowest `n` bits set.90///91/// Use [`DmaMask::new`] or [`DmaMask::try_new`] to construct a value. Values92/// are guaranteed to never exceed the bit width of `u64`.93///94/// This is the Rust equivalent of the C macro `DMA_BIT_MASK()`.95#[derive(Debug, Clone, Copy, PartialEq, Eq)]96pub struct DmaMask(u64);9798impl DmaMask {99/// Constructs a `DmaMask` with the lowest `n` bits set to `1`.100///101/// For `n <= 64`, sets exactly the lowest `n` bits.102/// For `n > 64`, results in a build error.103///104/// # Examples105///106/// ```107/// use kernel::dma::DmaMask;108///109/// let mask0 = DmaMask::new::<0>();110/// assert_eq!(mask0.value(), 0);111///112/// let mask1 = DmaMask::new::<1>();113/// assert_eq!(mask1.value(), 0b1);114///115/// let mask64 = DmaMask::new::<64>();116/// assert_eq!(mask64.value(), u64::MAX);117///118/// // Build failure.119/// // let mask_overflow = DmaMask::new::<100>();120/// ```121#[inline]122pub const fn new<const N: u32>() -> Self {123let Ok(mask) = Self::try_new(N) else {124build_error!("Invalid DMA Mask.");125};126127mask128}129130/// Constructs a `DmaMask` with the lowest `n` bits set to `1`.131///132/// For `n <= 64`, sets exactly the lowest `n` bits.133/// For `n > 64`, returns [`EINVAL`].134///135/// # Examples136///137/// ```138/// use kernel::dma::DmaMask;139///140/// let mask0 = DmaMask::try_new(0)?;141/// assert_eq!(mask0.value(), 0);142///143/// let mask1 = DmaMask::try_new(1)?;144/// assert_eq!(mask1.value(), 0b1);145///146/// let mask64 = DmaMask::try_new(64)?;147/// assert_eq!(mask64.value(), u64::MAX);148///149/// let mask_overflow = DmaMask::try_new(100);150/// assert!(mask_overflow.is_err());151/// # Ok::<(), Error>(())152/// ```153#[inline]154pub const fn try_new(n: u32) -> Result<Self> {155Ok(Self(match n {1560 => 0,1571..=64 => u64::MAX >> (64 - n),158_ => return Err(EINVAL),159}))160}161162/// Returns the underlying `u64` bitmask value.163#[inline]164pub const fn value(&self) -> u64 {165self.0166}167}168169/// Possible attributes associated with a DMA mapping.170///171/// They can be combined with the operators `|`, `&`, and `!`.172///173/// Values can be used from the [`attrs`] module.174///175/// # Examples176///177/// ```178/// # use kernel::device::{Bound, Device};179/// use kernel::dma::{attrs::*, CoherentAllocation};180///181/// # fn test(dev: &Device<Bound>) -> Result {182/// let attribs = DMA_ATTR_FORCE_CONTIGUOUS | DMA_ATTR_NO_WARN;183/// let c: CoherentAllocation<u64> =184/// CoherentAllocation::alloc_attrs(dev, 4, GFP_KERNEL, attribs)?;185/// # Ok::<(), Error>(()) }186/// ```187#[derive(Clone, Copy, PartialEq)]188#[repr(transparent)]189pub struct Attrs(u32);190191impl Attrs {192/// Get the raw representation of this attribute.193pub(crate) fn as_raw(self) -> crate::ffi::c_ulong {194self.0 as crate::ffi::c_ulong195}196197/// Check whether `flags` is contained in `self`.198pub fn contains(self, flags: Attrs) -> bool {199(self & flags) == flags200}201}202203impl core::ops::BitOr for Attrs {204type Output = Self;205fn bitor(self, rhs: Self) -> Self::Output {206Self(self.0 | rhs.0)207}208}209210impl core::ops::BitAnd for Attrs {211type Output = Self;212fn bitand(self, rhs: Self) -> Self::Output {213Self(self.0 & rhs.0)214}215}216217impl core::ops::Not for Attrs {218type Output = Self;219fn not(self) -> Self::Output {220Self(!self.0)221}222}223224/// DMA mapping attributes.225pub mod attrs {226use super::Attrs;227228/// Specifies that reads and writes to the mapping may be weakly ordered, that is that reads229/// and writes may pass each other.230pub const DMA_ATTR_WEAK_ORDERING: Attrs = Attrs(bindings::DMA_ATTR_WEAK_ORDERING);231232/// Specifies that writes to the mapping may be buffered to improve performance.233pub const DMA_ATTR_WRITE_COMBINE: Attrs = Attrs(bindings::DMA_ATTR_WRITE_COMBINE);234235/// Lets the platform to avoid creating a kernel virtual mapping for the allocated buffer.236pub const DMA_ATTR_NO_KERNEL_MAPPING: Attrs = Attrs(bindings::DMA_ATTR_NO_KERNEL_MAPPING);237238/// Allows platform code to skip synchronization of the CPU cache for the given buffer assuming239/// that it has been already transferred to 'device' domain.240pub const DMA_ATTR_SKIP_CPU_SYNC: Attrs = Attrs(bindings::DMA_ATTR_SKIP_CPU_SYNC);241242/// Forces contiguous allocation of the buffer in physical memory.243pub const DMA_ATTR_FORCE_CONTIGUOUS: Attrs = Attrs(bindings::DMA_ATTR_FORCE_CONTIGUOUS);244245/// Hints DMA-mapping subsystem that it's probably not worth the time to try246/// to allocate memory to in a way that gives better TLB efficiency.247pub const DMA_ATTR_ALLOC_SINGLE_PAGES: Attrs = Attrs(bindings::DMA_ATTR_ALLOC_SINGLE_PAGES);248249/// This tells the DMA-mapping subsystem to suppress allocation failure reports (similarly to250/// `__GFP_NOWARN`).251pub const DMA_ATTR_NO_WARN: Attrs = Attrs(bindings::DMA_ATTR_NO_WARN);252253/// Indicates that the buffer is fully accessible at an elevated privilege level (and254/// ideally inaccessible or at least read-only at lesser-privileged levels).255pub const DMA_ATTR_PRIVILEGED: Attrs = Attrs(bindings::DMA_ATTR_PRIVILEGED);256257/// Indicates that the buffer is MMIO memory.258pub const DMA_ATTR_MMIO: Attrs = Attrs(bindings::DMA_ATTR_MMIO);259}260261/// DMA data direction.262///263/// Corresponds to the C [`enum dma_data_direction`].264///265/// [`enum dma_data_direction`]: srctree/include/linux/dma-direction.h266#[derive(Copy, Clone, PartialEq, Eq, Debug)]267#[repr(u32)]268pub enum DataDirection {269/// The DMA mapping is for bidirectional data transfer.270///271/// This is used when the buffer can be both read from and written to by the device.272/// The cache for the corresponding memory region is both flushed and invalidated.273Bidirectional = Self::const_cast(bindings::dma_data_direction_DMA_BIDIRECTIONAL),274275/// The DMA mapping is for data transfer from memory to the device (write).276///277/// The CPU has prepared data in the buffer, and the device will read it.278/// The cache for the corresponding memory region is flushed before device access.279ToDevice = Self::const_cast(bindings::dma_data_direction_DMA_TO_DEVICE),280281/// The DMA mapping is for data transfer from the device to memory (read).282///283/// The device will write data into the buffer for the CPU to read.284/// The cache for the corresponding memory region is invalidated before CPU access.285FromDevice = Self::const_cast(bindings::dma_data_direction_DMA_FROM_DEVICE),286287/// The DMA mapping is not for data transfer.288///289/// This is primarily for debugging purposes. With this direction, the DMA mapping API290/// will not perform any cache coherency operations.291None = Self::const_cast(bindings::dma_data_direction_DMA_NONE),292}293294impl DataDirection {295/// Casts the bindgen-generated enum type to a `u32` at compile time.296///297/// This function will cause a compile-time error if the underlying value of the298/// C enum is out of bounds for `u32`.299const fn const_cast(val: bindings::dma_data_direction) -> u32 {300// CAST: The C standard allows compilers to choose different integer types for enums.301// To safely check the value, we cast it to a wide signed integer type (`i128`)302// which can hold any standard C integer enum type without truncation.303let wide_val = val as i128;304305// Check if the value is outside the valid range for the target type `u32`.306// CAST: `u32::MAX` is cast to `i128` to match the type of `wide_val` for the comparison.307if wide_val < 0 || wide_val > u32::MAX as i128 {308// Trigger a compile-time error in a const context.309build_error!("C enum value is out of bounds for the target type `u32`.");310}311312// CAST: This cast is valid because the check above guarantees that `wide_val`313// is within the representable range of `u32`.314wide_val as u32315}316}317318impl From<DataDirection> for bindings::dma_data_direction {319/// Returns the raw representation of [`enum dma_data_direction`].320fn from(direction: DataDirection) -> Self {321// CAST: `direction as u32` gets the underlying representation of our `#[repr(u32)]` enum.322// The subsequent cast to `Self` (the bindgen type) assumes the C enum is compatible323// with the enum variants of `DataDirection`, which is a valid assumption given our324// compile-time checks.325direction as u32 as Self326}327}328329/// An abstraction of the `dma_alloc_coherent` API.330///331/// This is an abstraction around the `dma_alloc_coherent` API which is used to allocate and map332/// large coherent DMA regions.333///334/// A [`CoherentAllocation`] instance contains a pointer to the allocated region (in the335/// processor's virtual address space) and the device address which can be given to the device336/// as the DMA address base of the region. The region is released once [`CoherentAllocation`]337/// is dropped.338///339/// # Invariants340///341/// - For the lifetime of an instance of [`CoherentAllocation`], the `cpu_addr` is a valid pointer342/// to an allocated region of coherent memory and `dma_handle` is the DMA address base of the343/// region.344/// - The size in bytes of the allocation is equal to `size_of::<T> * count`.345/// - `size_of::<T> * count` fits into a `usize`.346// TODO347//348// DMA allocations potentially carry device resources (e.g.IOMMU mappings), hence for soundness349// reasons DMA allocation would need to be embedded in a `Devres` container, in order to ensure350// that device resources can never survive device unbind.351//352// However, it is neither desirable nor necessary to protect the allocated memory of the DMA353// allocation from surviving device unbind; it would require RCU read side critical sections to354// access the memory, which may require subsequent unnecessary copies.355//356// Hence, find a way to revoke the device resources of a `CoherentAllocation`, but not the357// entire `CoherentAllocation` including the allocated memory itself.358pub struct CoherentAllocation<T: AsBytes + FromBytes> {359dev: ARef<device::Device>,360dma_handle: DmaAddress,361count: usize,362cpu_addr: NonNull<T>,363dma_attrs: Attrs,364}365366impl<T: AsBytes + FromBytes> CoherentAllocation<T> {367/// Allocates a region of `size_of::<T> * count` of coherent memory.368///369/// # Examples370///371/// ```372/// # use kernel::device::{Bound, Device};373/// use kernel::dma::{attrs::*, CoherentAllocation};374///375/// # fn test(dev: &Device<Bound>) -> Result {376/// let c: CoherentAllocation<u64> =377/// CoherentAllocation::alloc_attrs(dev, 4, GFP_KERNEL, DMA_ATTR_NO_WARN)?;378/// # Ok::<(), Error>(()) }379/// ```380pub fn alloc_attrs(381dev: &device::Device<Bound>,382count: usize,383gfp_flags: kernel::alloc::Flags,384dma_attrs: Attrs,385) -> Result<CoherentAllocation<T>> {386build_assert!(387core::mem::size_of::<T>() > 0,388"It doesn't make sense for the allocated type to be a ZST"389);390391let size = count392.checked_mul(core::mem::size_of::<T>())393.ok_or(EOVERFLOW)?;394let mut dma_handle = 0;395// SAFETY: Device pointer is guaranteed as valid by the type invariant on `Device`.396let addr = unsafe {397bindings::dma_alloc_attrs(398dev.as_raw(),399size,400&mut dma_handle,401gfp_flags.as_raw(),402dma_attrs.as_raw(),403)404};405let addr = NonNull::new(addr).ok_or(ENOMEM)?;406// INVARIANT:407// - We just successfully allocated a coherent region which is accessible for408// `count` elements, hence the cpu address is valid. We also hold a refcounted reference409// to the device.410// - The allocated `size` is equal to `size_of::<T> * count`.411// - The allocated `size` fits into a `usize`.412Ok(Self {413dev: dev.into(),414dma_handle,415count,416cpu_addr: addr.cast(),417dma_attrs,418})419}420421/// Performs the same functionality as [`CoherentAllocation::alloc_attrs`], except the422/// `dma_attrs` is 0 by default.423pub fn alloc_coherent(424dev: &device::Device<Bound>,425count: usize,426gfp_flags: kernel::alloc::Flags,427) -> Result<CoherentAllocation<T>> {428CoherentAllocation::alloc_attrs(dev, count, gfp_flags, Attrs(0))429}430431/// Returns the number of elements `T` in this allocation.432///433/// Note that this is not the size of the allocation in bytes, which is provided by434/// [`Self::size`].435pub fn count(&self) -> usize {436self.count437}438439/// Returns the size in bytes of this allocation.440pub fn size(&self) -> usize {441// INVARIANT: The type invariant of `Self` guarantees that `size_of::<T> * count` fits into442// a `usize`.443self.count * core::mem::size_of::<T>()444}445446/// Returns the base address to the allocated region in the CPU's virtual address space.447pub fn start_ptr(&self) -> *const T {448self.cpu_addr.as_ptr()449}450451/// Returns the base address to the allocated region in the CPU's virtual address space as452/// a mutable pointer.453pub fn start_ptr_mut(&mut self) -> *mut T {454self.cpu_addr.as_ptr()455}456457/// Returns a DMA handle which may be given to the device as the DMA address base of458/// the region.459pub fn dma_handle(&self) -> DmaAddress {460self.dma_handle461}462463/// Returns a DMA handle starting at `offset` (in units of `T`) which may be given to the464/// device as the DMA address base of the region.465///466/// Returns `EINVAL` if `offset` is not within the bounds of the allocation.467pub fn dma_handle_with_offset(&self, offset: usize) -> Result<DmaAddress> {468if offset >= self.count {469Err(EINVAL)470} else {471// INVARIANT: The type invariant of `Self` guarantees that `size_of::<T> * count` fits472// into a `usize`, and `offset` is inferior to `count`.473Ok(self.dma_handle + (offset * core::mem::size_of::<T>()) as DmaAddress)474}475}476477/// Common helper to validate a range applied from the allocated region in the CPU's virtual478/// address space.479fn validate_range(&self, offset: usize, count: usize) -> Result {480if offset.checked_add(count).ok_or(EOVERFLOW)? > self.count {481return Err(EINVAL);482}483Ok(())484}485486/// Returns the data from the region starting from `offset` as a slice.487/// `offset` and `count` are in units of `T`, not the number of bytes.488///489/// For ringbuffer type of r/w access or use-cases where the pointer to the live data is needed,490/// [`CoherentAllocation::start_ptr`] or [`CoherentAllocation::start_ptr_mut`] could be used491/// instead.492///493/// # Safety494///495/// * Callers must ensure that the device does not read/write to/from memory while the returned496/// slice is live.497/// * Callers must ensure that this call does not race with a write to the same region while498/// the returned slice is live.499pub unsafe fn as_slice(&self, offset: usize, count: usize) -> Result<&[T]> {500self.validate_range(offset, count)?;501// SAFETY:502// - The pointer is valid due to type invariant on `CoherentAllocation`,503// we've just checked that the range and index is within bounds. The immutability of the504// data is also guaranteed by the safety requirements of the function.505// - `offset + count` can't overflow since it is smaller than `self.count` and we've checked506// that `self.count` won't overflow early in the constructor.507Ok(unsafe { core::slice::from_raw_parts(self.start_ptr().add(offset), count) })508}509510/// Performs the same functionality as [`CoherentAllocation::as_slice`], except that a mutable511/// slice is returned.512///513/// # Safety514///515/// * Callers must ensure that the device does not read/write to/from memory while the returned516/// slice is live.517/// * Callers must ensure that this call does not race with a read or write to the same region518/// while the returned slice is live.519pub unsafe fn as_slice_mut(&mut self, offset: usize, count: usize) -> Result<&mut [T]> {520self.validate_range(offset, count)?;521// SAFETY:522// - The pointer is valid due to type invariant on `CoherentAllocation`,523// we've just checked that the range and index is within bounds. The immutability of the524// data is also guaranteed by the safety requirements of the function.525// - `offset + count` can't overflow since it is smaller than `self.count` and we've checked526// that `self.count` won't overflow early in the constructor.527Ok(unsafe { core::slice::from_raw_parts_mut(self.start_ptr_mut().add(offset), count) })528}529530/// Writes data to the region starting from `offset`. `offset` is in units of `T`, not the531/// number of bytes.532///533/// # Safety534///535/// * Callers must ensure that this call does not race with a read or write to the same region536/// that overlaps with this write.537///538/// # Examples539///540/// ```541/// # fn test(alloc: &mut kernel::dma::CoherentAllocation<u8>) -> Result {542/// let somedata: [u8; 4] = [0xf; 4];543/// let buf: &[u8] = &somedata;544/// // SAFETY: There is no concurrent HW operation on the device and no other R/W access to the545/// // region.546/// unsafe { alloc.write(buf, 0)?; }547/// # Ok::<(), Error>(()) }548/// ```549pub unsafe fn write(&mut self, src: &[T], offset: usize) -> Result {550self.validate_range(offset, src.len())?;551// SAFETY:552// - The pointer is valid due to type invariant on `CoherentAllocation`553// and we've just checked that the range and index is within bounds.554// - `offset + count` can't overflow since it is smaller than `self.count` and we've checked555// that `self.count` won't overflow early in the constructor.556unsafe {557core::ptr::copy_nonoverlapping(558src.as_ptr(),559self.start_ptr_mut().add(offset),560src.len(),561)562};563Ok(())564}565566/// Returns a pointer to an element from the region with bounds checking. `offset` is in567/// units of `T`, not the number of bytes.568///569/// Public but hidden since it should only be used from [`dma_read`] and [`dma_write`] macros.570#[doc(hidden)]571pub fn item_from_index(&self, offset: usize) -> Result<*mut T> {572if offset >= self.count {573return Err(EINVAL);574}575// SAFETY:576// - The pointer is valid due to type invariant on `CoherentAllocation`577// and we've just checked that the range and index is within bounds.578// - `offset` can't overflow since it is smaller than `self.count` and we've checked579// that `self.count` won't overflow early in the constructor.580Ok(unsafe { self.cpu_addr.as_ptr().add(offset) })581}582583/// Reads the value of `field` and ensures that its type is [`FromBytes`].584///585/// # Safety586///587/// This must be called from the [`dma_read`] macro which ensures that the `field` pointer is588/// validated beforehand.589///590/// Public but hidden since it should only be used from [`dma_read`] macro.591#[doc(hidden)]592pub unsafe fn field_read<F: FromBytes>(&self, field: *const F) -> F {593// SAFETY:594// - By the safety requirements field is valid.595// - Using read_volatile() here is not sound as per the usual rules, the usage here is596// a special exception with the following notes in place. When dealing with a potential597// race from a hardware or code outside kernel (e.g. user-space program), we need that598// read on a valid memory is not UB. Currently read_volatile() is used for this, and the599// rationale behind is that it should generate the same code as READ_ONCE() which the600// kernel already relies on to avoid UB on data races. Note that the usage of601// read_volatile() is limited to this particular case, it cannot be used to prevent602// the UB caused by racing between two kernel functions nor do they provide atomicity.603unsafe { field.read_volatile() }604}605606/// Writes a value to `field` and ensures that its type is [`AsBytes`].607///608/// # Safety609///610/// This must be called from the [`dma_write`] macro which ensures that the `field` pointer is611/// validated beforehand.612///613/// Public but hidden since it should only be used from [`dma_write`] macro.614#[doc(hidden)]615pub unsafe fn field_write<F: AsBytes>(&self, field: *mut F, val: F) {616// SAFETY:617// - By the safety requirements field is valid.618// - Using write_volatile() here is not sound as per the usual rules, the usage here is619// a special exception with the following notes in place. When dealing with a potential620// race from a hardware or code outside kernel (e.g. user-space program), we need that621// write on a valid memory is not UB. Currently write_volatile() is used for this, and the622// rationale behind is that it should generate the same code as WRITE_ONCE() which the623// kernel already relies on to avoid UB on data races. Note that the usage of624// write_volatile() is limited to this particular case, it cannot be used to prevent625// the UB caused by racing between two kernel functions nor do they provide atomicity.626unsafe { field.write_volatile(val) }627}628}629630/// Note that the device configured to do DMA must be halted before this object is dropped.631impl<T: AsBytes + FromBytes> Drop for CoherentAllocation<T> {632fn drop(&mut self) {633let size = self.count * core::mem::size_of::<T>();634// SAFETY: Device pointer is guaranteed as valid by the type invariant on `Device`.635// The cpu address, and the dma handle are valid due to the type invariants on636// `CoherentAllocation`.637unsafe {638bindings::dma_free_attrs(639self.dev.as_raw(),640size,641self.start_ptr_mut().cast(),642self.dma_handle,643self.dma_attrs.as_raw(),644)645}646}647}648649// SAFETY: It is safe to send a `CoherentAllocation` to another thread if `T`650// can be sent to another thread.651unsafe impl<T: AsBytes + FromBytes + Send> Send for CoherentAllocation<T> {}652653/// Reads a field of an item from an allocated region of structs.654///655/// # Examples656///657/// ```658/// use kernel::device::Device;659/// use kernel::dma::{attrs::*, CoherentAllocation};660///661/// struct MyStruct { field: u32, }662///663/// // SAFETY: All bit patterns are acceptable values for `MyStruct`.664/// unsafe impl kernel::transmute::FromBytes for MyStruct{};665/// // SAFETY: Instances of `MyStruct` have no uninitialized portions.666/// unsafe impl kernel::transmute::AsBytes for MyStruct{};667///668/// # fn test(alloc: &kernel::dma::CoherentAllocation<MyStruct>) -> Result {669/// let whole = kernel::dma_read!(alloc[2]);670/// let field = kernel::dma_read!(alloc[1].field);671/// # Ok::<(), Error>(()) }672/// ```673#[macro_export]674macro_rules! dma_read {675($dma:expr, $idx: expr, $($field:tt)*) => {{676(|| -> ::core::result::Result<_, $crate::error::Error> {677let item = $crate::dma::CoherentAllocation::item_from_index(&$dma, $idx)?;678// SAFETY: `item_from_index` ensures that `item` is always a valid pointer and can be679// dereferenced. The compiler also further validates the expression on whether `field`680// is a member of `item` when expanded by the macro.681unsafe {682let ptr_field = ::core::ptr::addr_of!((*item) $($field)*);683::core::result::Result::Ok(684$crate::dma::CoherentAllocation::field_read(&$dma, ptr_field)685)686}687})()688}};689($dma:ident [ $idx:expr ] $($field:tt)* ) => {690$crate::dma_read!($dma, $idx, $($field)*)691};692($($dma:ident).* [ $idx:expr ] $($field:tt)* ) => {693$crate::dma_read!($($dma).*, $idx, $($field)*)694};695}696697/// Writes to a field of an item from an allocated region of structs.698///699/// # Examples700///701/// ```702/// use kernel::device::Device;703/// use kernel::dma::{attrs::*, CoherentAllocation};704///705/// struct MyStruct { member: u32, }706///707/// // SAFETY: All bit patterns are acceptable values for `MyStruct`.708/// unsafe impl kernel::transmute::FromBytes for MyStruct{};709/// // SAFETY: Instances of `MyStruct` have no uninitialized portions.710/// unsafe impl kernel::transmute::AsBytes for MyStruct{};711///712/// # fn test(alloc: &kernel::dma::CoherentAllocation<MyStruct>) -> Result {713/// kernel::dma_write!(alloc[2].member = 0xf);714/// kernel::dma_write!(alloc[1] = MyStruct { member: 0xf });715/// # Ok::<(), Error>(()) }716/// ```717#[macro_export]718macro_rules! dma_write {719($dma:ident [ $idx:expr ] $($field:tt)*) => {{720$crate::dma_write!($dma, $idx, $($field)*)721}};722($($dma:ident).* [ $idx:expr ] $($field:tt)* ) => {{723$crate::dma_write!($($dma).*, $idx, $($field)*)724}};725($dma:expr, $idx: expr, = $val:expr) => {726(|| -> ::core::result::Result<_, $crate::error::Error> {727let item = $crate::dma::CoherentAllocation::item_from_index(&$dma, $idx)?;728// SAFETY: `item_from_index` ensures that `item` is always a valid item.729unsafe { $crate::dma::CoherentAllocation::field_write(&$dma, item, $val) }730::core::result::Result::Ok(())731})()732};733($dma:expr, $idx: expr, $(.$field:ident)* = $val:expr) => {734(|| -> ::core::result::Result<_, $crate::error::Error> {735let item = $crate::dma::CoherentAllocation::item_from_index(&$dma, $idx)?;736// SAFETY: `item_from_index` ensures that `item` is always a valid pointer and can be737// dereferenced. The compiler also further validates the expression on whether `field`738// is a member of `item` when expanded by the macro.739unsafe {740let ptr_field = ::core::ptr::addr_of_mut!((*item) $(.$field)*);741$crate::dma::CoherentAllocation::field_write(&$dma, ptr_field, $val)742}743::core::result::Result::Ok(())744})()745};746}747748749