// 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};1415/// DMA address type.16///17/// Represents a bus address used for Direct Memory Access (DMA) operations.18///19/// This is an alias of the kernel's `dma_addr_t`, which may be `u32` or `u64` depending on20/// `CONFIG_ARCH_DMA_ADDR_T_64BIT`.21///22/// Note that this may be `u64` even on 32-bit architectures.23pub type DmaAddress = bindings::dma_addr_t;2425/// Trait to be implemented by DMA capable bus devices.26///27/// The [`dma::Device`](Device) trait should be implemented by bus specific device representations,28/// where the underlying bus is DMA capable, such as [`pci::Device`](::kernel::pci::Device) or29/// [`platform::Device`](::kernel::platform::Device).30pub trait Device: AsRef<device::Device<Core>> {31/// Set up the device's DMA streaming addressing capabilities.32///33/// This method is usually called once from `probe()` as soon as the device capabilities are34/// known.35///36/// # Safety37///38/// This method must not be called concurrently with any DMA allocation or mapping primitives,39/// such as [`CoherentAllocation::alloc_attrs`].40unsafe fn dma_set_mask(&self, mask: DmaMask) -> Result {41// SAFETY:42// - By the type invariant of `device::Device`, `self.as_ref().as_raw()` is valid.43// - The safety requirement of this function guarantees that there are no concurrent calls44// to DMA allocation and mapping primitives using this mask.45to_result(unsafe { bindings::dma_set_mask(self.as_ref().as_raw(), mask.value()) })46}4748/// Set up the device's DMA coherent addressing capabilities.49///50/// This method is usually called once from `probe()` as soon as the device capabilities are51/// known.52///53/// # Safety54///55/// This method must not be called concurrently with any DMA allocation or mapping primitives,56/// such as [`CoherentAllocation::alloc_attrs`].57unsafe fn dma_set_coherent_mask(&self, mask: DmaMask) -> Result {58// SAFETY:59// - By the type invariant of `device::Device`, `self.as_ref().as_raw()` is valid.60// - The safety requirement of this function guarantees that there are no concurrent calls61// to DMA allocation and mapping primitives using this mask.62to_result(unsafe { bindings::dma_set_coherent_mask(self.as_ref().as_raw(), mask.value()) })63}6465/// Set up the device's DMA addressing capabilities.66///67/// This is a combination of [`Device::dma_set_mask`] and [`Device::dma_set_coherent_mask`].68///69/// This method is usually called once from `probe()` as soon as the device capabilities are70/// known.71///72/// # Safety73///74/// This method must not be called concurrently with any DMA allocation or mapping primitives,75/// such as [`CoherentAllocation::alloc_attrs`].76unsafe fn dma_set_mask_and_coherent(&self, mask: DmaMask) -> Result {77// SAFETY:78// - By the type invariant of `device::Device`, `self.as_ref().as_raw()` is valid.79// - The safety requirement of this function guarantees that there are no concurrent calls80// to DMA allocation and mapping primitives using this mask.81to_result(unsafe {82bindings::dma_set_mask_and_coherent(self.as_ref().as_raw(), mask.value())83})84}85}8687/// A DMA mask that holds a bitmask with the lowest `n` bits set.88///89/// Use [`DmaMask::new`] or [`DmaMask::try_new`] to construct a value. Values90/// are guaranteed to never exceed the bit width of `u64`.91///92/// This is the Rust equivalent of the C macro `DMA_BIT_MASK()`.93#[derive(Debug, Clone, Copy, PartialEq, Eq)]94pub struct DmaMask(u64);9596impl DmaMask {97/// Constructs a `DmaMask` with the lowest `n` bits set to `1`.98///99/// For `n <= 64`, sets exactly the lowest `n` bits.100/// For `n > 64`, results in a build error.101///102/// # Examples103///104/// ```105/// use kernel::dma::DmaMask;106///107/// let mask0 = DmaMask::new::<0>();108/// assert_eq!(mask0.value(), 0);109///110/// let mask1 = DmaMask::new::<1>();111/// assert_eq!(mask1.value(), 0b1);112///113/// let mask64 = DmaMask::new::<64>();114/// assert_eq!(mask64.value(), u64::MAX);115///116/// // Build failure.117/// // let mask_overflow = DmaMask::new::<100>();118/// ```119#[inline]120pub const fn new<const N: u32>() -> Self {121let Ok(mask) = Self::try_new(N) else {122build_error!("Invalid DMA Mask.");123};124125mask126}127128/// Constructs a `DmaMask` with the lowest `n` bits set to `1`.129///130/// For `n <= 64`, sets exactly the lowest `n` bits.131/// For `n > 64`, returns [`EINVAL`].132///133/// # Examples134///135/// ```136/// use kernel::dma::DmaMask;137///138/// let mask0 = DmaMask::try_new(0)?;139/// assert_eq!(mask0.value(), 0);140///141/// let mask1 = DmaMask::try_new(1)?;142/// assert_eq!(mask1.value(), 0b1);143///144/// let mask64 = DmaMask::try_new(64)?;145/// assert_eq!(mask64.value(), u64::MAX);146///147/// let mask_overflow = DmaMask::try_new(100);148/// assert!(mask_overflow.is_err());149/// # Ok::<(), Error>(())150/// ```151#[inline]152pub const fn try_new(n: u32) -> Result<Self> {153Ok(Self(match n {1540 => 0,1551..=64 => u64::MAX >> (64 - n),156_ => return Err(EINVAL),157}))158}159160/// Returns the underlying `u64` bitmask value.161#[inline]162pub const fn value(&self) -> u64 {163self.0164}165}166167/// Possible attributes associated with a DMA mapping.168///169/// They can be combined with the operators `|`, `&`, and `!`.170///171/// Values can be used from the [`attrs`] module.172///173/// # Examples174///175/// ```176/// # use kernel::device::{Bound, Device};177/// use kernel::dma::{attrs::*, CoherentAllocation};178///179/// # fn test(dev: &Device<Bound>) -> Result {180/// let attribs = DMA_ATTR_FORCE_CONTIGUOUS | DMA_ATTR_NO_WARN;181/// let c: CoherentAllocation<u64> =182/// CoherentAllocation::alloc_attrs(dev, 4, GFP_KERNEL, attribs)?;183/// # Ok::<(), Error>(()) }184/// ```185#[derive(Clone, Copy, PartialEq)]186#[repr(transparent)]187pub struct Attrs(u32);188189impl Attrs {190/// Get the raw representation of this attribute.191pub(crate) fn as_raw(self) -> crate::ffi::c_ulong {192self.0 as crate::ffi::c_ulong193}194195/// Check whether `flags` is contained in `self`.196pub fn contains(self, flags: Attrs) -> bool {197(self & flags) == flags198}199}200201impl core::ops::BitOr for Attrs {202type Output = Self;203fn bitor(self, rhs: Self) -> Self::Output {204Self(self.0 | rhs.0)205}206}207208impl core::ops::BitAnd for Attrs {209type Output = Self;210fn bitand(self, rhs: Self) -> Self::Output {211Self(self.0 & rhs.0)212}213}214215impl core::ops::Not for Attrs {216type Output = Self;217fn not(self) -> Self::Output {218Self(!self.0)219}220}221222/// DMA mapping attributes.223pub mod attrs {224use super::Attrs;225226/// Specifies that reads and writes to the mapping may be weakly ordered, that is that reads227/// and writes may pass each other.228pub const DMA_ATTR_WEAK_ORDERING: Attrs = Attrs(bindings::DMA_ATTR_WEAK_ORDERING);229230/// Specifies that writes to the mapping may be buffered to improve performance.231pub const DMA_ATTR_WRITE_COMBINE: Attrs = Attrs(bindings::DMA_ATTR_WRITE_COMBINE);232233/// Lets the platform to avoid creating a kernel virtual mapping for the allocated buffer.234pub const DMA_ATTR_NO_KERNEL_MAPPING: Attrs = Attrs(bindings::DMA_ATTR_NO_KERNEL_MAPPING);235236/// Allows platform code to skip synchronization of the CPU cache for the given buffer assuming237/// that it has been already transferred to 'device' domain.238pub const DMA_ATTR_SKIP_CPU_SYNC: Attrs = Attrs(bindings::DMA_ATTR_SKIP_CPU_SYNC);239240/// Forces contiguous allocation of the buffer in physical memory.241pub const DMA_ATTR_FORCE_CONTIGUOUS: Attrs = Attrs(bindings::DMA_ATTR_FORCE_CONTIGUOUS);242243/// Hints DMA-mapping subsystem that it's probably not worth the time to try244/// to allocate memory to in a way that gives better TLB efficiency.245pub const DMA_ATTR_ALLOC_SINGLE_PAGES: Attrs = Attrs(bindings::DMA_ATTR_ALLOC_SINGLE_PAGES);246247/// This tells the DMA-mapping subsystem to suppress allocation failure reports (similarly to248/// `__GFP_NOWARN`).249pub const DMA_ATTR_NO_WARN: Attrs = Attrs(bindings::DMA_ATTR_NO_WARN);250251/// Indicates that the buffer is fully accessible at an elevated privilege level (and252/// ideally inaccessible or at least read-only at lesser-privileged levels).253pub const DMA_ATTR_PRIVILEGED: Attrs = Attrs(bindings::DMA_ATTR_PRIVILEGED);254255/// Indicates that the buffer is MMIO memory.256pub const DMA_ATTR_MMIO: Attrs = Attrs(bindings::DMA_ATTR_MMIO);257}258259/// DMA data direction.260///261/// Corresponds to the C [`enum dma_data_direction`].262///263/// [`enum dma_data_direction`]: srctree/include/linux/dma-direction.h264#[derive(Copy, Clone, PartialEq, Eq, Debug)]265#[repr(u32)]266pub enum DataDirection {267/// The DMA mapping is for bidirectional data transfer.268///269/// This is used when the buffer can be both read from and written to by the device.270/// The cache for the corresponding memory region is both flushed and invalidated.271Bidirectional = Self::const_cast(bindings::dma_data_direction_DMA_BIDIRECTIONAL),272273/// The DMA mapping is for data transfer from memory to the device (write).274///275/// The CPU has prepared data in the buffer, and the device will read it.276/// The cache for the corresponding memory region is flushed before device access.277ToDevice = Self::const_cast(bindings::dma_data_direction_DMA_TO_DEVICE),278279/// The DMA mapping is for data transfer from the device to memory (read).280///281/// The device will write data into the buffer for the CPU to read.282/// The cache for the corresponding memory region is invalidated before CPU access.283FromDevice = Self::const_cast(bindings::dma_data_direction_DMA_FROM_DEVICE),284285/// The DMA mapping is not for data transfer.286///287/// This is primarily for debugging purposes. With this direction, the DMA mapping API288/// will not perform any cache coherency operations.289None = Self::const_cast(bindings::dma_data_direction_DMA_NONE),290}291292impl DataDirection {293/// Casts the bindgen-generated enum type to a `u32` at compile time.294///295/// This function will cause a compile-time error if the underlying value of the296/// C enum is out of bounds for `u32`.297const fn const_cast(val: bindings::dma_data_direction) -> u32 {298// CAST: The C standard allows compilers to choose different integer types for enums.299// To safely check the value, we cast it to a wide signed integer type (`i128`)300// which can hold any standard C integer enum type without truncation.301let wide_val = val as i128;302303// Check if the value is outside the valid range for the target type `u32`.304// CAST: `u32::MAX` is cast to `i128` to match the type of `wide_val` for the comparison.305if wide_val < 0 || wide_val > u32::MAX as i128 {306// Trigger a compile-time error in a const context.307build_error!("C enum value is out of bounds for the target type `u32`.");308}309310// CAST: This cast is valid because the check above guarantees that `wide_val`311// is within the representable range of `u32`.312wide_val as u32313}314}315316impl From<DataDirection> for bindings::dma_data_direction {317/// Returns the raw representation of [`enum dma_data_direction`].318fn from(direction: DataDirection) -> Self {319// CAST: `direction as u32` gets the underlying representation of our `#[repr(u32)]` enum.320// The subsequent cast to `Self` (the bindgen type) assumes the C enum is compatible321// with the enum variants of `DataDirection`, which is a valid assumption given our322// compile-time checks.323direction as u32 as Self324}325}326327/// An abstraction of the `dma_alloc_coherent` API.328///329/// This is an abstraction around the `dma_alloc_coherent` API which is used to allocate and map330/// large coherent DMA regions.331///332/// A [`CoherentAllocation`] instance contains a pointer to the allocated region (in the333/// processor's virtual address space) and the device address which can be given to the device334/// as the DMA address base of the region. The region is released once [`CoherentAllocation`]335/// is dropped.336///337/// # Invariants338///339/// - For the lifetime of an instance of [`CoherentAllocation`], the `cpu_addr` is a valid pointer340/// to an allocated region of coherent memory and `dma_handle` is the DMA address base of the341/// region.342/// - The size in bytes of the allocation is equal to `size_of::<T> * count`.343/// - `size_of::<T> * count` fits into a `usize`.344// TODO345//346// DMA allocations potentially carry device resources (e.g.IOMMU mappings), hence for soundness347// reasons DMA allocation would need to be embedded in a `Devres` container, in order to ensure348// that device resources can never survive device unbind.349//350// However, it is neither desirable nor necessary to protect the allocated memory of the DMA351// allocation from surviving device unbind; it would require RCU read side critical sections to352// access the memory, which may require subsequent unnecessary copies.353//354// Hence, find a way to revoke the device resources of a `CoherentAllocation`, but not the355// entire `CoherentAllocation` including the allocated memory itself.356pub struct CoherentAllocation<T: AsBytes + FromBytes> {357dev: ARef<device::Device>,358dma_handle: DmaAddress,359count: usize,360cpu_addr: *mut T,361dma_attrs: Attrs,362}363364impl<T: AsBytes + FromBytes> CoherentAllocation<T> {365/// Allocates a region of `size_of::<T> * count` of coherent memory.366///367/// # Examples368///369/// ```370/// # use kernel::device::{Bound, Device};371/// use kernel::dma::{attrs::*, CoherentAllocation};372///373/// # fn test(dev: &Device<Bound>) -> Result {374/// let c: CoherentAllocation<u64> =375/// CoherentAllocation::alloc_attrs(dev, 4, GFP_KERNEL, DMA_ATTR_NO_WARN)?;376/// # Ok::<(), Error>(()) }377/// ```378pub fn alloc_attrs(379dev: &device::Device<Bound>,380count: usize,381gfp_flags: kernel::alloc::Flags,382dma_attrs: Attrs,383) -> Result<CoherentAllocation<T>> {384build_assert!(385core::mem::size_of::<T>() > 0,386"It doesn't make sense for the allocated type to be a ZST"387);388389let size = count390.checked_mul(core::mem::size_of::<T>())391.ok_or(EOVERFLOW)?;392let mut dma_handle = 0;393// SAFETY: Device pointer is guaranteed as valid by the type invariant on `Device`.394let ret = unsafe {395bindings::dma_alloc_attrs(396dev.as_raw(),397size,398&mut dma_handle,399gfp_flags.as_raw(),400dma_attrs.as_raw(),401)402};403if ret.is_null() {404return Err(ENOMEM);405}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: ret.cast::<T>(),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_addr449}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_addr455}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.cpu_addr.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.cpu_addr.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 the device does not read/write to/from memory while the returned536/// slice is live.537/// * Callers must ensure that this call does not race with a read or write to the same region538/// that overlaps with this write.539///540/// # Examples541///542/// ```543/// # fn test(alloc: &mut kernel::dma::CoherentAllocation<u8>) -> Result {544/// let somedata: [u8; 4] = [0xf; 4];545/// let buf: &[u8] = &somedata;546/// // SAFETY: There is no concurrent HW operation on the device and no other R/W access to the547/// // region.548/// unsafe { alloc.write(buf, 0)?; }549/// # Ok::<(), Error>(()) }550/// ```551pub unsafe fn write(&mut self, src: &[T], offset: usize) -> Result {552self.validate_range(offset, src.len())?;553// SAFETY:554// - The pointer is valid due to type invariant on `CoherentAllocation`555// and we've just checked that the range and index is within bounds.556// - `offset + count` can't overflow since it is smaller than `self.count` and we've checked557// that `self.count` won't overflow early in the constructor.558unsafe {559core::ptr::copy_nonoverlapping(src.as_ptr(), self.cpu_addr.add(offset), src.len())560};561Ok(())562}563564/// Returns a pointer to an element from the region with bounds checking. `offset` is in565/// units of `T`, not the number of bytes.566///567/// Public but hidden since it should only be used from [`dma_read`] and [`dma_write`] macros.568#[doc(hidden)]569pub fn item_from_index(&self, offset: usize) -> Result<*mut T> {570if offset >= self.count {571return Err(EINVAL);572}573// SAFETY:574// - The pointer is valid due to type invariant on `CoherentAllocation`575// and we've just checked that the range and index is within bounds.576// - `offset` can't overflow since it is smaller than `self.count` and we've checked577// that `self.count` won't overflow early in the constructor.578Ok(unsafe { self.cpu_addr.add(offset) })579}580581/// Reads the value of `field` and ensures that its type is [`FromBytes`].582///583/// # Safety584///585/// This must be called from the [`dma_read`] macro which ensures that the `field` pointer is586/// validated beforehand.587///588/// Public but hidden since it should only be used from [`dma_read`] macro.589#[doc(hidden)]590pub unsafe fn field_read<F: FromBytes>(&self, field: *const F) -> F {591// SAFETY:592// - By the safety requirements field is valid.593// - Using read_volatile() here is not sound as per the usual rules, the usage here is594// a special exception with the following notes in place. When dealing with a potential595// race from a hardware or code outside kernel (e.g. user-space program), we need that596// read on a valid memory is not UB. Currently read_volatile() is used for this, and the597// rationale behind is that it should generate the same code as READ_ONCE() which the598// kernel already relies on to avoid UB on data races. Note that the usage of599// read_volatile() is limited to this particular case, it cannot be used to prevent600// the UB caused by racing between two kernel functions nor do they provide atomicity.601unsafe { field.read_volatile() }602}603604/// Writes a value to `field` and ensures that its type is [`AsBytes`].605///606/// # Safety607///608/// This must be called from the [`dma_write`] macro which ensures that the `field` pointer is609/// validated beforehand.610///611/// Public but hidden since it should only be used from [`dma_write`] macro.612#[doc(hidden)]613pub unsafe fn field_write<F: AsBytes>(&self, field: *mut F, val: F) {614// SAFETY:615// - By the safety requirements field is valid.616// - Using write_volatile() here is not sound as per the usual rules, the usage here is617// a special exception with the following notes in place. When dealing with a potential618// race from a hardware or code outside kernel (e.g. user-space program), we need that619// write on a valid memory is not UB. Currently write_volatile() is used for this, and the620// rationale behind is that it should generate the same code as WRITE_ONCE() which the621// kernel already relies on to avoid UB on data races. Note that the usage of622// write_volatile() is limited to this particular case, it cannot be used to prevent623// the UB caused by racing between two kernel functions nor do they provide atomicity.624unsafe { field.write_volatile(val) }625}626}627628/// Note that the device configured to do DMA must be halted before this object is dropped.629impl<T: AsBytes + FromBytes> Drop for CoherentAllocation<T> {630fn drop(&mut self) {631let size = self.count * core::mem::size_of::<T>();632// SAFETY: Device pointer is guaranteed as valid by the type invariant on `Device`.633// The cpu address, and the dma handle are valid due to the type invariants on634// `CoherentAllocation`.635unsafe {636bindings::dma_free_attrs(637self.dev.as_raw(),638size,639self.cpu_addr.cast(),640self.dma_handle,641self.dma_attrs.as_raw(),642)643}644}645}646647// SAFETY: It is safe to send a `CoherentAllocation` to another thread if `T`648// can be sent to another thread.649unsafe impl<T: AsBytes + FromBytes + Send> Send for CoherentAllocation<T> {}650651/// Reads a field of an item from an allocated region of structs.652///653/// # Examples654///655/// ```656/// use kernel::device::Device;657/// use kernel::dma::{attrs::*, CoherentAllocation};658///659/// struct MyStruct { field: u32, }660///661/// // SAFETY: All bit patterns are acceptable values for `MyStruct`.662/// unsafe impl kernel::transmute::FromBytes for MyStruct{};663/// // SAFETY: Instances of `MyStruct` have no uninitialized portions.664/// unsafe impl kernel::transmute::AsBytes for MyStruct{};665///666/// # fn test(alloc: &kernel::dma::CoherentAllocation<MyStruct>) -> Result {667/// let whole = kernel::dma_read!(alloc[2]);668/// let field = kernel::dma_read!(alloc[1].field);669/// # Ok::<(), Error>(()) }670/// ```671#[macro_export]672macro_rules! dma_read {673($dma:expr, $idx: expr, $($field:tt)*) => {{674(|| -> ::core::result::Result<_, $crate::error::Error> {675let item = $crate::dma::CoherentAllocation::item_from_index(&$dma, $idx)?;676// SAFETY: `item_from_index` ensures that `item` is always a valid pointer and can be677// dereferenced. The compiler also further validates the expression on whether `field`678// is a member of `item` when expanded by the macro.679unsafe {680let ptr_field = ::core::ptr::addr_of!((*item) $($field)*);681::core::result::Result::Ok(682$crate::dma::CoherentAllocation::field_read(&$dma, ptr_field)683)684}685})()686}};687($dma:ident [ $idx:expr ] $($field:tt)* ) => {688$crate::dma_read!($dma, $idx, $($field)*)689};690($($dma:ident).* [ $idx:expr ] $($field:tt)* ) => {691$crate::dma_read!($($dma).*, $idx, $($field)*)692};693}694695/// Writes to a field of an item from an allocated region of structs.696///697/// # Examples698///699/// ```700/// use kernel::device::Device;701/// use kernel::dma::{attrs::*, CoherentAllocation};702///703/// struct MyStruct { member: u32, }704///705/// // SAFETY: All bit patterns are acceptable values for `MyStruct`.706/// unsafe impl kernel::transmute::FromBytes for MyStruct{};707/// // SAFETY: Instances of `MyStruct` have no uninitialized portions.708/// unsafe impl kernel::transmute::AsBytes for MyStruct{};709///710/// # fn test(alloc: &kernel::dma::CoherentAllocation<MyStruct>) -> Result {711/// kernel::dma_write!(alloc[2].member = 0xf);712/// kernel::dma_write!(alloc[1] = MyStruct { member: 0xf });713/// # Ok::<(), Error>(()) }714/// ```715#[macro_export]716macro_rules! dma_write {717($dma:ident [ $idx:expr ] $($field:tt)*) => {{718$crate::dma_write!($dma, $idx, $($field)*)719}};720($($dma:ident).* [ $idx:expr ] $($field:tt)* ) => {{721$crate::dma_write!($($dma).*, $idx, $($field)*)722}};723($dma:expr, $idx: expr, = $val:expr) => {724(|| -> ::core::result::Result<_, $crate::error::Error> {725let item = $crate::dma::CoherentAllocation::item_from_index(&$dma, $idx)?;726// SAFETY: `item_from_index` ensures that `item` is always a valid item.727unsafe { $crate::dma::CoherentAllocation::field_write(&$dma, item, $val) }728::core::result::Result::Ok(())729})()730};731($dma:expr, $idx: expr, $(.$field:ident)* = $val:expr) => {732(|| -> ::core::result::Result<_, $crate::error::Error> {733let item = $crate::dma::CoherentAllocation::item_from_index(&$dma, $idx)?;734// SAFETY: `item_from_index` ensures that `item` is always a valid pointer and can be735// dereferenced. The compiler also further validates the expression on whether `field`736// is a member of `item` when expanded by the macro.737unsafe {738let ptr_field = ::core::ptr::addr_of_mut!((*item) $(.$field)*);739$crate::dma::CoherentAllocation::field_write(&$dma, ptr_field, $val)740}741::core::result::Result::Ok(())742})()743};744}745746747