// 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);254}255256/// DMA data direction.257///258/// Corresponds to the C [`enum dma_data_direction`].259///260/// [`enum dma_data_direction`]: srctree/include/linux/dma-direction.h261#[derive(Copy, Clone, PartialEq, Eq, Debug)]262#[repr(u32)]263pub enum DataDirection {264/// The DMA mapping is for bidirectional data transfer.265///266/// This is used when the buffer can be both read from and written to by the device.267/// The cache for the corresponding memory region is both flushed and invalidated.268Bidirectional = Self::const_cast(bindings::dma_data_direction_DMA_BIDIRECTIONAL),269270/// The DMA mapping is for data transfer from memory to the device (write).271///272/// The CPU has prepared data in the buffer, and the device will read it.273/// The cache for the corresponding memory region is flushed before device access.274ToDevice = Self::const_cast(bindings::dma_data_direction_DMA_TO_DEVICE),275276/// The DMA mapping is for data transfer from the device to memory (read).277///278/// The device will write data into the buffer for the CPU to read.279/// The cache for the corresponding memory region is invalidated before CPU access.280FromDevice = Self::const_cast(bindings::dma_data_direction_DMA_FROM_DEVICE),281282/// The DMA mapping is not for data transfer.283///284/// This is primarily for debugging purposes. With this direction, the DMA mapping API285/// will not perform any cache coherency operations.286None = Self::const_cast(bindings::dma_data_direction_DMA_NONE),287}288289impl DataDirection {290/// Casts the bindgen-generated enum type to a `u32` at compile time.291///292/// This function will cause a compile-time error if the underlying value of the293/// C enum is out of bounds for `u32`.294const fn const_cast(val: bindings::dma_data_direction) -> u32 {295// CAST: The C standard allows compilers to choose different integer types for enums.296// To safely check the value, we cast it to a wide signed integer type (`i128`)297// which can hold any standard C integer enum type without truncation.298let wide_val = val as i128;299300// Check if the value is outside the valid range for the target type `u32`.301// CAST: `u32::MAX` is cast to `i128` to match the type of `wide_val` for the comparison.302if wide_val < 0 || wide_val > u32::MAX as i128 {303// Trigger a compile-time error in a const context.304build_error!("C enum value is out of bounds for the target type `u32`.");305}306307// CAST: This cast is valid because the check above guarantees that `wide_val`308// is within the representable range of `u32`.309wide_val as u32310}311}312313impl From<DataDirection> for bindings::dma_data_direction {314/// Returns the raw representation of [`enum dma_data_direction`].315fn from(direction: DataDirection) -> Self {316// CAST: `direction as u32` gets the underlying representation of our `#[repr(u32)]` enum.317// The subsequent cast to `Self` (the bindgen type) assumes the C enum is compatible318// with the enum variants of `DataDirection`, which is a valid assumption given our319// compile-time checks.320direction as u32 as Self321}322}323324/// An abstraction of the `dma_alloc_coherent` API.325///326/// This is an abstraction around the `dma_alloc_coherent` API which is used to allocate and map327/// large coherent DMA regions.328///329/// A [`CoherentAllocation`] instance contains a pointer to the allocated region (in the330/// processor's virtual address space) and the device address which can be given to the device331/// as the DMA address base of the region. The region is released once [`CoherentAllocation`]332/// is dropped.333///334/// # Invariants335///336/// - For the lifetime of an instance of [`CoherentAllocation`], the `cpu_addr` is a valid pointer337/// to an allocated region of coherent memory and `dma_handle` is the DMA address base of the338/// region.339/// - The size in bytes of the allocation is equal to `size_of::<T> * count`.340/// - `size_of::<T> * count` fits into a `usize`.341// TODO342//343// DMA allocations potentially carry device resources (e.g.IOMMU mappings), hence for soundness344// reasons DMA allocation would need to be embedded in a `Devres` container, in order to ensure345// that device resources can never survive device unbind.346//347// However, it is neither desirable nor necessary to protect the allocated memory of the DMA348// allocation from surviving device unbind; it would require RCU read side critical sections to349// access the memory, which may require subsequent unnecessary copies.350//351// Hence, find a way to revoke the device resources of a `CoherentAllocation`, but not the352// entire `CoherentAllocation` including the allocated memory itself.353pub struct CoherentAllocation<T: AsBytes + FromBytes> {354dev: ARef<device::Device>,355dma_handle: DmaAddress,356count: usize,357cpu_addr: *mut T,358dma_attrs: Attrs,359}360361impl<T: AsBytes + FromBytes> CoherentAllocation<T> {362/// Allocates a region of `size_of::<T> * count` of coherent memory.363///364/// # Examples365///366/// ```367/// # use kernel::device::{Bound, Device};368/// use kernel::dma::{attrs::*, CoherentAllocation};369///370/// # fn test(dev: &Device<Bound>) -> Result {371/// let c: CoherentAllocation<u64> =372/// CoherentAllocation::alloc_attrs(dev, 4, GFP_KERNEL, DMA_ATTR_NO_WARN)?;373/// # Ok::<(), Error>(()) }374/// ```375pub fn alloc_attrs(376dev: &device::Device<Bound>,377count: usize,378gfp_flags: kernel::alloc::Flags,379dma_attrs: Attrs,380) -> Result<CoherentAllocation<T>> {381build_assert!(382core::mem::size_of::<T>() > 0,383"It doesn't make sense for the allocated type to be a ZST"384);385386let size = count387.checked_mul(core::mem::size_of::<T>())388.ok_or(EOVERFLOW)?;389let mut dma_handle = 0;390// SAFETY: Device pointer is guaranteed as valid by the type invariant on `Device`.391let ret = unsafe {392bindings::dma_alloc_attrs(393dev.as_raw(),394size,395&mut dma_handle,396gfp_flags.as_raw(),397dma_attrs.as_raw(),398)399};400if ret.is_null() {401return Err(ENOMEM);402}403// INVARIANT:404// - We just successfully allocated a coherent region which is accessible for405// `count` elements, hence the cpu address is valid. We also hold a refcounted reference406// to the device.407// - The allocated `size` is equal to `size_of::<T> * count`.408// - The allocated `size` fits into a `usize`.409Ok(Self {410dev: dev.into(),411dma_handle,412count,413cpu_addr: ret.cast::<T>(),414dma_attrs,415})416}417418/// Performs the same functionality as [`CoherentAllocation::alloc_attrs`], except the419/// `dma_attrs` is 0 by default.420pub fn alloc_coherent(421dev: &device::Device<Bound>,422count: usize,423gfp_flags: kernel::alloc::Flags,424) -> Result<CoherentAllocation<T>> {425CoherentAllocation::alloc_attrs(dev, count, gfp_flags, Attrs(0))426}427428/// Returns the number of elements `T` in this allocation.429///430/// Note that this is not the size of the allocation in bytes, which is provided by431/// [`Self::size`].432pub fn count(&self) -> usize {433self.count434}435436/// Returns the size in bytes of this allocation.437pub fn size(&self) -> usize {438// INVARIANT: The type invariant of `Self` guarantees that `size_of::<T> * count` fits into439// a `usize`.440self.count * core::mem::size_of::<T>()441}442443/// Returns the base address to the allocated region in the CPU's virtual address space.444pub fn start_ptr(&self) -> *const T {445self.cpu_addr446}447448/// Returns the base address to the allocated region in the CPU's virtual address space as449/// a mutable pointer.450pub fn start_ptr_mut(&mut self) -> *mut T {451self.cpu_addr452}453454/// Returns a DMA handle which may be given to the device as the DMA address base of455/// the region.456pub fn dma_handle(&self) -> DmaAddress {457self.dma_handle458}459460/// Returns a DMA handle starting at `offset` (in units of `T`) which may be given to the461/// device as the DMA address base of the region.462///463/// Returns `EINVAL` if `offset` is not within the bounds of the allocation.464pub fn dma_handle_with_offset(&self, offset: usize) -> Result<DmaAddress> {465if offset >= self.count {466Err(EINVAL)467} else {468// INVARIANT: The type invariant of `Self` guarantees that `size_of::<T> * count` fits469// into a `usize`, and `offset` is inferior to `count`.470Ok(self.dma_handle + (offset * core::mem::size_of::<T>()) as DmaAddress)471}472}473474/// Common helper to validate a range applied from the allocated region in the CPU's virtual475/// address space.476fn validate_range(&self, offset: usize, count: usize) -> Result {477if offset.checked_add(count).ok_or(EOVERFLOW)? > self.count {478return Err(EINVAL);479}480Ok(())481}482483/// Returns the data from the region starting from `offset` as a slice.484/// `offset` and `count` are in units of `T`, not the number of bytes.485///486/// For ringbuffer type of r/w access or use-cases where the pointer to the live data is needed,487/// [`CoherentAllocation::start_ptr`] or [`CoherentAllocation::start_ptr_mut`] could be used488/// instead.489///490/// # Safety491///492/// * Callers must ensure that the device does not read/write to/from memory while the returned493/// slice is live.494/// * Callers must ensure that this call does not race with a write to the same region while495/// the returned slice is live.496pub unsafe fn as_slice(&self, offset: usize, count: usize) -> Result<&[T]> {497self.validate_range(offset, count)?;498// SAFETY:499// - The pointer is valid due to type invariant on `CoherentAllocation`,500// we've just checked that the range and index is within bounds. The immutability of the501// data is also guaranteed by the safety requirements of the function.502// - `offset + count` can't overflow since it is smaller than `self.count` and we've checked503// that `self.count` won't overflow early in the constructor.504Ok(unsafe { core::slice::from_raw_parts(self.cpu_addr.add(offset), count) })505}506507/// Performs the same functionality as [`CoherentAllocation::as_slice`], except that a mutable508/// slice is returned.509///510/// # Safety511///512/// * Callers must ensure that the device does not read/write to/from memory while the returned513/// slice is live.514/// * Callers must ensure that this call does not race with a read or write to the same region515/// while the returned slice is live.516pub unsafe fn as_slice_mut(&mut self, offset: usize, count: usize) -> Result<&mut [T]> {517self.validate_range(offset, count)?;518// SAFETY:519// - The pointer is valid due to type invariant on `CoherentAllocation`,520// we've just checked that the range and index is within bounds. The immutability of the521// data is also guaranteed by the safety requirements of the function.522// - `offset + count` can't overflow since it is smaller than `self.count` and we've checked523// that `self.count` won't overflow early in the constructor.524Ok(unsafe { core::slice::from_raw_parts_mut(self.cpu_addr.add(offset), count) })525}526527/// Writes data to the region starting from `offset`. `offset` is in units of `T`, not the528/// number of bytes.529///530/// # Safety531///532/// * Callers must ensure that the device does not read/write to/from memory while the returned533/// slice is live.534/// * Callers must ensure that this call does not race with a read or write to the same region535/// that overlaps with this write.536///537/// # Examples538///539/// ```540/// # fn test(alloc: &mut kernel::dma::CoherentAllocation<u8>) -> Result {541/// let somedata: [u8; 4] = [0xf; 4];542/// let buf: &[u8] = &somedata;543/// // SAFETY: There is no concurrent HW operation on the device and no other R/W access to the544/// // region.545/// unsafe { alloc.write(buf, 0)?; }546/// # Ok::<(), Error>(()) }547/// ```548pub unsafe fn write(&mut self, src: &[T], offset: usize) -> Result {549self.validate_range(offset, src.len())?;550// SAFETY:551// - The pointer is valid due to type invariant on `CoherentAllocation`552// and we've just checked that the range and index is within bounds.553// - `offset + count` can't overflow since it is smaller than `self.count` and we've checked554// that `self.count` won't overflow early in the constructor.555unsafe {556core::ptr::copy_nonoverlapping(src.as_ptr(), self.cpu_addr.add(offset), src.len())557};558Ok(())559}560561/// Returns a pointer to an element from the region with bounds checking. `offset` is in562/// units of `T`, not the number of bytes.563///564/// Public but hidden since it should only be used from [`dma_read`] and [`dma_write`] macros.565#[doc(hidden)]566pub fn item_from_index(&self, offset: usize) -> Result<*mut T> {567if offset >= self.count {568return Err(EINVAL);569}570// SAFETY:571// - The pointer is valid due to type invariant on `CoherentAllocation`572// and we've just checked that the range and index is within bounds.573// - `offset` can't overflow since it is smaller than `self.count` and we've checked574// that `self.count` won't overflow early in the constructor.575Ok(unsafe { self.cpu_addr.add(offset) })576}577578/// Reads the value of `field` and ensures that its type is [`FromBytes`].579///580/// # Safety581///582/// This must be called from the [`dma_read`] macro which ensures that the `field` pointer is583/// validated beforehand.584///585/// Public but hidden since it should only be used from [`dma_read`] macro.586#[doc(hidden)]587pub unsafe fn field_read<F: FromBytes>(&self, field: *const F) -> F {588// SAFETY:589// - By the safety requirements field is valid.590// - Using read_volatile() here is not sound as per the usual rules, the usage here is591// a special exception with the following notes in place. When dealing with a potential592// race from a hardware or code outside kernel (e.g. user-space program), we need that593// read on a valid memory is not UB. Currently read_volatile() is used for this, and the594// rationale behind is that it should generate the same code as READ_ONCE() which the595// kernel already relies on to avoid UB on data races. Note that the usage of596// read_volatile() is limited to this particular case, it cannot be used to prevent597// the UB caused by racing between two kernel functions nor do they provide atomicity.598unsafe { field.read_volatile() }599}600601/// Writes a value to `field` and ensures that its type is [`AsBytes`].602///603/// # Safety604///605/// This must be called from the [`dma_write`] macro which ensures that the `field` pointer is606/// validated beforehand.607///608/// Public but hidden since it should only be used from [`dma_write`] macro.609#[doc(hidden)]610pub unsafe fn field_write<F: AsBytes>(&self, field: *mut F, val: F) {611// SAFETY:612// - By the safety requirements field is valid.613// - Using write_volatile() here is not sound as per the usual rules, the usage here is614// a special exception with the following notes in place. When dealing with a potential615// race from a hardware or code outside kernel (e.g. user-space program), we need that616// write on a valid memory is not UB. Currently write_volatile() is used for this, and the617// rationale behind is that it should generate the same code as WRITE_ONCE() which the618// kernel already relies on to avoid UB on data races. Note that the usage of619// write_volatile() is limited to this particular case, it cannot be used to prevent620// the UB caused by racing between two kernel functions nor do they provide atomicity.621unsafe { field.write_volatile(val) }622}623}624625/// Note that the device configured to do DMA must be halted before this object is dropped.626impl<T: AsBytes + FromBytes> Drop for CoherentAllocation<T> {627fn drop(&mut self) {628let size = self.count * core::mem::size_of::<T>();629// SAFETY: Device pointer is guaranteed as valid by the type invariant on `Device`.630// The cpu address, and the dma handle are valid due to the type invariants on631// `CoherentAllocation`.632unsafe {633bindings::dma_free_attrs(634self.dev.as_raw(),635size,636self.cpu_addr.cast(),637self.dma_handle,638self.dma_attrs.as_raw(),639)640}641}642}643644// SAFETY: It is safe to send a `CoherentAllocation` to another thread if `T`645// can be sent to another thread.646unsafe impl<T: AsBytes + FromBytes + Send> Send for CoherentAllocation<T> {}647648/// Reads a field of an item from an allocated region of structs.649///650/// # Examples651///652/// ```653/// use kernel::device::Device;654/// use kernel::dma::{attrs::*, CoherentAllocation};655///656/// struct MyStruct { field: u32, }657///658/// // SAFETY: All bit patterns are acceptable values for `MyStruct`.659/// unsafe impl kernel::transmute::FromBytes for MyStruct{};660/// // SAFETY: Instances of `MyStruct` have no uninitialized portions.661/// unsafe impl kernel::transmute::AsBytes for MyStruct{};662///663/// # fn test(alloc: &kernel::dma::CoherentAllocation<MyStruct>) -> Result {664/// let whole = kernel::dma_read!(alloc[2]);665/// let field = kernel::dma_read!(alloc[1].field);666/// # Ok::<(), Error>(()) }667/// ```668#[macro_export]669macro_rules! dma_read {670($dma:expr, $idx: expr, $($field:tt)*) => {{671(|| -> ::core::result::Result<_, $crate::error::Error> {672let item = $crate::dma::CoherentAllocation::item_from_index(&$dma, $idx)?;673// SAFETY: `item_from_index` ensures that `item` is always a valid pointer and can be674// dereferenced. The compiler also further validates the expression on whether `field`675// is a member of `item` when expanded by the macro.676unsafe {677let ptr_field = ::core::ptr::addr_of!((*item) $($field)*);678::core::result::Result::Ok(679$crate::dma::CoherentAllocation::field_read(&$dma, ptr_field)680)681}682})()683}};684($dma:ident [ $idx:expr ] $($field:tt)* ) => {685$crate::dma_read!($dma, $idx, $($field)*)686};687($($dma:ident).* [ $idx:expr ] $($field:tt)* ) => {688$crate::dma_read!($($dma).*, $idx, $($field)*)689};690}691692/// Writes to a field of an item from an allocated region of structs.693///694/// # Examples695///696/// ```697/// use kernel::device::Device;698/// use kernel::dma::{attrs::*, CoherentAllocation};699///700/// struct MyStruct { member: u32, }701///702/// // SAFETY: All bit patterns are acceptable values for `MyStruct`.703/// unsafe impl kernel::transmute::FromBytes for MyStruct{};704/// // SAFETY: Instances of `MyStruct` have no uninitialized portions.705/// unsafe impl kernel::transmute::AsBytes for MyStruct{};706///707/// # fn test(alloc: &kernel::dma::CoherentAllocation<MyStruct>) -> Result {708/// kernel::dma_write!(alloc[2].member = 0xf);709/// kernel::dma_write!(alloc[1] = MyStruct { member: 0xf });710/// # Ok::<(), Error>(()) }711/// ```712#[macro_export]713macro_rules! dma_write {714($dma:ident [ $idx:expr ] $($field:tt)*) => {{715$crate::dma_write!($dma, $idx, $($field)*)716}};717($($dma:ident).* [ $idx:expr ] $($field:tt)* ) => {{718$crate::dma_write!($($dma).*, $idx, $($field)*)719}};720($dma:expr, $idx: expr, = $val:expr) => {721(|| -> ::core::result::Result<_, $crate::error::Error> {722let item = $crate::dma::CoherentAllocation::item_from_index(&$dma, $idx)?;723// SAFETY: `item_from_index` ensures that `item` is always a valid item.724unsafe { $crate::dma::CoherentAllocation::field_write(&$dma, item, $val) }725::core::result::Result::Ok(())726})()727};728($dma:expr, $idx: expr, $(.$field:ident)* = $val:expr) => {729(|| -> ::core::result::Result<_, $crate::error::Error> {730let item = $crate::dma::CoherentAllocation::item_from_index(&$dma, $idx)?;731// SAFETY: `item_from_index` ensures that `item` is always a valid pointer and can be732// dereferenced. The compiler also further validates the expression on whether `field`733// is a member of `item` when expanded by the macro.734unsafe {735let ptr_field = ::core::ptr::addr_of_mut!((*item) $(.$field)*);736$crate::dma::CoherentAllocation::field_write(&$dma, ptr_field, $val)737}738::core::result::Result::Ok(())739})()740};741}742743744