xref: /linux/rust/kernel/dma.rs (revision ec7714e4947909190ffb3041a03311a975350fe0)
1ad2907b4SAbdiel Janulgue // SPDX-License-Identifier: GPL-2.0
2ad2907b4SAbdiel Janulgue 
3ad2907b4SAbdiel Janulgue //! Direct memory access (DMA).
4ad2907b4SAbdiel Janulgue //!
5ad2907b4SAbdiel Janulgue //! C header: [`include/linux/dma-mapping.h`](srctree/include/linux/dma-mapping.h)
6ad2907b4SAbdiel Janulgue 
7ad2907b4SAbdiel Janulgue use crate::{
8ad2907b4SAbdiel Janulgue     bindings, build_assert,
97bd1710aSDanilo Krummrich     device::{Bound, Device},
10ad2907b4SAbdiel Janulgue     error::code::*,
11ad2907b4SAbdiel Janulgue     error::Result,
12ad2907b4SAbdiel Janulgue     transmute::{AsBytes, FromBytes},
13ad2907b4SAbdiel Janulgue     types::ARef,
14ad2907b4SAbdiel Janulgue };
15ad2907b4SAbdiel Janulgue 
16ad2907b4SAbdiel Janulgue /// Possible attributes associated with a DMA mapping.
17ad2907b4SAbdiel Janulgue ///
18ad2907b4SAbdiel Janulgue /// They can be combined with the operators `|`, `&`, and `!`.
19ad2907b4SAbdiel Janulgue ///
20ad2907b4SAbdiel Janulgue /// Values can be used from the [`attrs`] module.
21ad2907b4SAbdiel Janulgue ///
22ad2907b4SAbdiel Janulgue /// # Examples
23ad2907b4SAbdiel Janulgue ///
24ad2907b4SAbdiel Janulgue /// ```
257bd1710aSDanilo Krummrich /// # use kernel::device::{Bound, Device};
26ad2907b4SAbdiel Janulgue /// use kernel::dma::{attrs::*, CoherentAllocation};
27ad2907b4SAbdiel Janulgue ///
287bd1710aSDanilo Krummrich /// # fn test(dev: &Device<Bound>) -> Result {
29ad2907b4SAbdiel Janulgue /// let attribs = DMA_ATTR_FORCE_CONTIGUOUS | DMA_ATTR_NO_WARN;
30ad2907b4SAbdiel Janulgue /// let c: CoherentAllocation<u64> =
31ad2907b4SAbdiel Janulgue ///     CoherentAllocation::alloc_attrs(dev, 4, GFP_KERNEL, attribs)?;
32ad2907b4SAbdiel Janulgue /// # Ok::<(), Error>(()) }
33ad2907b4SAbdiel Janulgue /// ```
34ad2907b4SAbdiel Janulgue #[derive(Clone, Copy, PartialEq)]
35ad2907b4SAbdiel Janulgue #[repr(transparent)]
36ad2907b4SAbdiel Janulgue pub struct Attrs(u32);
37ad2907b4SAbdiel Janulgue 
38ad2907b4SAbdiel Janulgue impl Attrs {
39ad2907b4SAbdiel Janulgue     /// Get the raw representation of this attribute.
as_raw(self) -> crate::ffi::c_ulong40ad2907b4SAbdiel Janulgue     pub(crate) fn as_raw(self) -> crate::ffi::c_ulong {
41ad2907b4SAbdiel Janulgue         self.0 as _
42ad2907b4SAbdiel Janulgue     }
43ad2907b4SAbdiel Janulgue 
44ad2907b4SAbdiel Janulgue     /// Check whether `flags` is contained in `self`.
contains(self, flags: Attrs) -> bool45ad2907b4SAbdiel Janulgue     pub fn contains(self, flags: Attrs) -> bool {
46ad2907b4SAbdiel Janulgue         (self & flags) == flags
47ad2907b4SAbdiel Janulgue     }
48ad2907b4SAbdiel Janulgue }
49ad2907b4SAbdiel Janulgue 
50ad2907b4SAbdiel Janulgue impl core::ops::BitOr for Attrs {
51ad2907b4SAbdiel Janulgue     type Output = Self;
bitor(self, rhs: Self) -> Self::Output52ad2907b4SAbdiel Janulgue     fn bitor(self, rhs: Self) -> Self::Output {
53ad2907b4SAbdiel Janulgue         Self(self.0 | rhs.0)
54ad2907b4SAbdiel Janulgue     }
55ad2907b4SAbdiel Janulgue }
56ad2907b4SAbdiel Janulgue 
57ad2907b4SAbdiel Janulgue impl core::ops::BitAnd for Attrs {
58ad2907b4SAbdiel Janulgue     type Output = Self;
bitand(self, rhs: Self) -> Self::Output59ad2907b4SAbdiel Janulgue     fn bitand(self, rhs: Self) -> Self::Output {
60ad2907b4SAbdiel Janulgue         Self(self.0 & rhs.0)
61ad2907b4SAbdiel Janulgue     }
62ad2907b4SAbdiel Janulgue }
63ad2907b4SAbdiel Janulgue 
64ad2907b4SAbdiel Janulgue impl core::ops::Not for Attrs {
65ad2907b4SAbdiel Janulgue     type Output = Self;
not(self) -> Self::Output66ad2907b4SAbdiel Janulgue     fn not(self) -> Self::Output {
67ad2907b4SAbdiel Janulgue         Self(!self.0)
68ad2907b4SAbdiel Janulgue     }
69ad2907b4SAbdiel Janulgue }
70ad2907b4SAbdiel Janulgue 
71ad2907b4SAbdiel Janulgue /// DMA mapping attributes.
72ad2907b4SAbdiel Janulgue pub mod attrs {
73ad2907b4SAbdiel Janulgue     use super::Attrs;
74ad2907b4SAbdiel Janulgue 
75ad2907b4SAbdiel Janulgue     /// Specifies that reads and writes to the mapping may be weakly ordered, that is that reads
76ad2907b4SAbdiel Janulgue     /// and writes may pass each other.
77ad2907b4SAbdiel Janulgue     pub const DMA_ATTR_WEAK_ORDERING: Attrs = Attrs(bindings::DMA_ATTR_WEAK_ORDERING);
78ad2907b4SAbdiel Janulgue 
79ad2907b4SAbdiel Janulgue     /// Specifies that writes to the mapping may be buffered to improve performance.
80ad2907b4SAbdiel Janulgue     pub const DMA_ATTR_WRITE_COMBINE: Attrs = Attrs(bindings::DMA_ATTR_WRITE_COMBINE);
81ad2907b4SAbdiel Janulgue 
82ad2907b4SAbdiel Janulgue     /// Lets the platform to avoid creating a kernel virtual mapping for the allocated buffer.
83ad2907b4SAbdiel Janulgue     pub const DMA_ATTR_NO_KERNEL_MAPPING: Attrs = Attrs(bindings::DMA_ATTR_NO_KERNEL_MAPPING);
84ad2907b4SAbdiel Janulgue 
85ad2907b4SAbdiel Janulgue     /// Allows platform code to skip synchronization of the CPU cache for the given buffer assuming
86ad2907b4SAbdiel Janulgue     /// that it has been already transferred to 'device' domain.
87ad2907b4SAbdiel Janulgue     pub const DMA_ATTR_SKIP_CPU_SYNC: Attrs = Attrs(bindings::DMA_ATTR_SKIP_CPU_SYNC);
88ad2907b4SAbdiel Janulgue 
89ad2907b4SAbdiel Janulgue     /// Forces contiguous allocation of the buffer in physical memory.
90ad2907b4SAbdiel Janulgue     pub const DMA_ATTR_FORCE_CONTIGUOUS: Attrs = Attrs(bindings::DMA_ATTR_FORCE_CONTIGUOUS);
91ad2907b4SAbdiel Janulgue 
92ad2907b4SAbdiel Janulgue     /// This is a hint to the DMA-mapping subsystem that it's probably not worth the time to try
93ad2907b4SAbdiel Janulgue     /// to allocate memory to in a way that gives better TLB efficiency.
94ad2907b4SAbdiel Janulgue     pub const DMA_ATTR_ALLOC_SINGLE_PAGES: Attrs = Attrs(bindings::DMA_ATTR_ALLOC_SINGLE_PAGES);
95ad2907b4SAbdiel Janulgue 
96ad2907b4SAbdiel Janulgue     /// This tells the DMA-mapping subsystem to suppress allocation failure reports (similarly to
97*df523db1SMiguel Ojeda     /// `__GFP_NOWARN`).
98ad2907b4SAbdiel Janulgue     pub const DMA_ATTR_NO_WARN: Attrs = Attrs(bindings::DMA_ATTR_NO_WARN);
99ad2907b4SAbdiel Janulgue 
100ad2907b4SAbdiel Janulgue     /// Used to indicate that the buffer is fully accessible at an elevated privilege level (and
101ad2907b4SAbdiel Janulgue     /// ideally inaccessible or at least read-only at lesser-privileged levels).
102ad2907b4SAbdiel Janulgue     pub const DMA_ATTR_PRIVILEGED: Attrs = Attrs(bindings::DMA_ATTR_PRIVILEGED);
103ad2907b4SAbdiel Janulgue }
104ad2907b4SAbdiel Janulgue 
105ad2907b4SAbdiel Janulgue /// An abstraction of the `dma_alloc_coherent` API.
106ad2907b4SAbdiel Janulgue ///
107ad2907b4SAbdiel Janulgue /// This is an abstraction around the `dma_alloc_coherent` API which is used to allocate and map
108ad2907b4SAbdiel Janulgue /// large consistent DMA regions.
109ad2907b4SAbdiel Janulgue ///
110ad2907b4SAbdiel Janulgue /// A [`CoherentAllocation`] instance contains a pointer to the allocated region (in the
111ad2907b4SAbdiel Janulgue /// processor's virtual address space) and the device address which can be given to the device
112ad2907b4SAbdiel Janulgue /// as the DMA address base of the region. The region is released once [`CoherentAllocation`]
113ad2907b4SAbdiel Janulgue /// is dropped.
114ad2907b4SAbdiel Janulgue ///
115ad2907b4SAbdiel Janulgue /// # Invariants
116ad2907b4SAbdiel Janulgue ///
117ad2907b4SAbdiel Janulgue /// For the lifetime of an instance of [`CoherentAllocation`], the `cpu_addr` is a valid pointer
118ad2907b4SAbdiel Janulgue /// to an allocated region of consistent memory and `dma_handle` is the DMA address base of
119ad2907b4SAbdiel Janulgue /// the region.
120ad2907b4SAbdiel Janulgue // TODO
121ad2907b4SAbdiel Janulgue //
122ad2907b4SAbdiel Janulgue // DMA allocations potentially carry device resources (e.g.IOMMU mappings), hence for soundness
123ad2907b4SAbdiel Janulgue // reasons DMA allocation would need to be embedded in a `Devres` container, in order to ensure
124ad2907b4SAbdiel Janulgue // that device resources can never survive device unbind.
125ad2907b4SAbdiel Janulgue //
126ad2907b4SAbdiel Janulgue // However, it is neither desirable nor necessary to protect the allocated memory of the DMA
127ad2907b4SAbdiel Janulgue // allocation from surviving device unbind; it would require RCU read side critical sections to
128ad2907b4SAbdiel Janulgue // access the memory, which may require subsequent unnecessary copies.
129ad2907b4SAbdiel Janulgue //
130ad2907b4SAbdiel Janulgue // Hence, find a way to revoke the device resources of a `CoherentAllocation`, but not the
131ad2907b4SAbdiel Janulgue // entire `CoherentAllocation` including the allocated memory itself.
132ad2907b4SAbdiel Janulgue pub struct CoherentAllocation<T: AsBytes + FromBytes> {
133ad2907b4SAbdiel Janulgue     dev: ARef<Device>,
134ad2907b4SAbdiel Janulgue     dma_handle: bindings::dma_addr_t,
135ad2907b4SAbdiel Janulgue     count: usize,
136ad2907b4SAbdiel Janulgue     cpu_addr: *mut T,
137ad2907b4SAbdiel Janulgue     dma_attrs: Attrs,
138ad2907b4SAbdiel Janulgue }
139ad2907b4SAbdiel Janulgue 
140ad2907b4SAbdiel Janulgue impl<T: AsBytes + FromBytes> CoherentAllocation<T> {
141ad2907b4SAbdiel Janulgue     /// Allocates a region of `size_of::<T> * count` of consistent memory.
142ad2907b4SAbdiel Janulgue     ///
143ad2907b4SAbdiel Janulgue     /// # Examples
144ad2907b4SAbdiel Janulgue     ///
145ad2907b4SAbdiel Janulgue     /// ```
1467bd1710aSDanilo Krummrich     /// # use kernel::device::{Bound, Device};
147ad2907b4SAbdiel Janulgue     /// use kernel::dma::{attrs::*, CoherentAllocation};
148ad2907b4SAbdiel Janulgue     ///
1497bd1710aSDanilo Krummrich     /// # fn test(dev: &Device<Bound>) -> Result {
150ad2907b4SAbdiel Janulgue     /// let c: CoherentAllocation<u64> =
151ad2907b4SAbdiel Janulgue     ///     CoherentAllocation::alloc_attrs(dev, 4, GFP_KERNEL, DMA_ATTR_NO_WARN)?;
152ad2907b4SAbdiel Janulgue     /// # Ok::<(), Error>(()) }
153ad2907b4SAbdiel Janulgue     /// ```
alloc_attrs( dev: &Device<Bound>, count: usize, gfp_flags: kernel::alloc::Flags, dma_attrs: Attrs, ) -> Result<CoherentAllocation<T>>154ad2907b4SAbdiel Janulgue     pub fn alloc_attrs(
1557bd1710aSDanilo Krummrich         dev: &Device<Bound>,
156ad2907b4SAbdiel Janulgue         count: usize,
157ad2907b4SAbdiel Janulgue         gfp_flags: kernel::alloc::Flags,
158ad2907b4SAbdiel Janulgue         dma_attrs: Attrs,
159ad2907b4SAbdiel Janulgue     ) -> Result<CoherentAllocation<T>> {
160ad2907b4SAbdiel Janulgue         build_assert!(
161ad2907b4SAbdiel Janulgue             core::mem::size_of::<T>() > 0,
162ad2907b4SAbdiel Janulgue             "It doesn't make sense for the allocated type to be a ZST"
163ad2907b4SAbdiel Janulgue         );
164ad2907b4SAbdiel Janulgue 
165ad2907b4SAbdiel Janulgue         let size = count
166ad2907b4SAbdiel Janulgue             .checked_mul(core::mem::size_of::<T>())
167ad2907b4SAbdiel Janulgue             .ok_or(EOVERFLOW)?;
168ad2907b4SAbdiel Janulgue         let mut dma_handle = 0;
169ad2907b4SAbdiel Janulgue         // SAFETY: Device pointer is guaranteed as valid by the type invariant on `Device`.
170ad2907b4SAbdiel Janulgue         let ret = unsafe {
171ad2907b4SAbdiel Janulgue             bindings::dma_alloc_attrs(
172ad2907b4SAbdiel Janulgue                 dev.as_raw(),
173ad2907b4SAbdiel Janulgue                 size,
174ad2907b4SAbdiel Janulgue                 &mut dma_handle,
175ad2907b4SAbdiel Janulgue                 gfp_flags.as_raw(),
176ad2907b4SAbdiel Janulgue                 dma_attrs.as_raw(),
177ad2907b4SAbdiel Janulgue             )
178ad2907b4SAbdiel Janulgue         };
179ad2907b4SAbdiel Janulgue         if ret.is_null() {
180ad2907b4SAbdiel Janulgue             return Err(ENOMEM);
181ad2907b4SAbdiel Janulgue         }
182ad2907b4SAbdiel Janulgue         // INVARIANT: We just successfully allocated a coherent region which is accessible for
183ad2907b4SAbdiel Janulgue         // `count` elements, hence the cpu address is valid. We also hold a refcounted reference
184ad2907b4SAbdiel Janulgue         // to the device.
185ad2907b4SAbdiel Janulgue         Ok(Self {
186ad2907b4SAbdiel Janulgue             dev: dev.into(),
187ad2907b4SAbdiel Janulgue             dma_handle,
188ad2907b4SAbdiel Janulgue             count,
189ad2907b4SAbdiel Janulgue             cpu_addr: ret as *mut T,
190ad2907b4SAbdiel Janulgue             dma_attrs,
191ad2907b4SAbdiel Janulgue         })
192ad2907b4SAbdiel Janulgue     }
193ad2907b4SAbdiel Janulgue 
194ad2907b4SAbdiel Janulgue     /// Performs the same functionality as [`CoherentAllocation::alloc_attrs`], except the
195ad2907b4SAbdiel Janulgue     /// `dma_attrs` is 0 by default.
alloc_coherent( dev: &Device<Bound>, count: usize, gfp_flags: kernel::alloc::Flags, ) -> Result<CoherentAllocation<T>>196ad2907b4SAbdiel Janulgue     pub fn alloc_coherent(
1977bd1710aSDanilo Krummrich         dev: &Device<Bound>,
198ad2907b4SAbdiel Janulgue         count: usize,
199ad2907b4SAbdiel Janulgue         gfp_flags: kernel::alloc::Flags,
200ad2907b4SAbdiel Janulgue     ) -> Result<CoherentAllocation<T>> {
201ad2907b4SAbdiel Janulgue         CoherentAllocation::alloc_attrs(dev, count, gfp_flags, Attrs(0))
202ad2907b4SAbdiel Janulgue     }
203ad2907b4SAbdiel Janulgue 
204ad2907b4SAbdiel Janulgue     /// Returns the base address to the allocated region in the CPU's virtual address space.
start_ptr(&self) -> *const T205ad2907b4SAbdiel Janulgue     pub fn start_ptr(&self) -> *const T {
206ad2907b4SAbdiel Janulgue         self.cpu_addr
207ad2907b4SAbdiel Janulgue     }
208ad2907b4SAbdiel Janulgue 
209ad2907b4SAbdiel Janulgue     /// Returns the base address to the allocated region in the CPU's virtual address space as
210ad2907b4SAbdiel Janulgue     /// a mutable pointer.
start_ptr_mut(&mut self) -> *mut T211ad2907b4SAbdiel Janulgue     pub fn start_ptr_mut(&mut self) -> *mut T {
212ad2907b4SAbdiel Janulgue         self.cpu_addr
213ad2907b4SAbdiel Janulgue     }
214ad2907b4SAbdiel Janulgue 
215ad2907b4SAbdiel Janulgue     /// Returns a DMA handle which may given to the device as the DMA address base of
216ad2907b4SAbdiel Janulgue     /// the region.
dma_handle(&self) -> bindings::dma_addr_t217ad2907b4SAbdiel Janulgue     pub fn dma_handle(&self) -> bindings::dma_addr_t {
218ad2907b4SAbdiel Janulgue         self.dma_handle
219ad2907b4SAbdiel Janulgue     }
220ad2907b4SAbdiel Janulgue 
221ad2907b4SAbdiel Janulgue     /// Returns a pointer to an element from the region with bounds checking. `offset` is in
222ad2907b4SAbdiel Janulgue     /// units of `T`, not the number of bytes.
223ad2907b4SAbdiel Janulgue     ///
224ad2907b4SAbdiel Janulgue     /// Public but hidden since it should only be used from [`dma_read`] and [`dma_write`] macros.
225ad2907b4SAbdiel Janulgue     #[doc(hidden)]
item_from_index(&self, offset: usize) -> Result<*mut T>226ad2907b4SAbdiel Janulgue     pub fn item_from_index(&self, offset: usize) -> Result<*mut T> {
227ad2907b4SAbdiel Janulgue         if offset >= self.count {
228ad2907b4SAbdiel Janulgue             return Err(EINVAL);
229ad2907b4SAbdiel Janulgue         }
230ad2907b4SAbdiel Janulgue         // SAFETY:
231ad2907b4SAbdiel Janulgue         // - The pointer is valid due to type invariant on `CoherentAllocation`
232ad2907b4SAbdiel Janulgue         // and we've just checked that the range and index is within bounds.
233ad2907b4SAbdiel Janulgue         // - `offset` can't overflow since it is smaller than `self.count` and we've checked
234ad2907b4SAbdiel Janulgue         // that `self.count` won't overflow early in the constructor.
235ad2907b4SAbdiel Janulgue         Ok(unsafe { self.cpu_addr.add(offset) })
236ad2907b4SAbdiel Janulgue     }
237ad2907b4SAbdiel Janulgue 
238ad2907b4SAbdiel Janulgue     /// Reads the value of `field` and ensures that its type is [`FromBytes`].
239ad2907b4SAbdiel Janulgue     ///
240ad2907b4SAbdiel Janulgue     /// # Safety
241ad2907b4SAbdiel Janulgue     ///
242ad2907b4SAbdiel Janulgue     /// This must be called from the [`dma_read`] macro which ensures that the `field` pointer is
243ad2907b4SAbdiel Janulgue     /// validated beforehand.
244ad2907b4SAbdiel Janulgue     ///
245ad2907b4SAbdiel Janulgue     /// Public but hidden since it should only be used from [`dma_read`] macro.
246ad2907b4SAbdiel Janulgue     #[doc(hidden)]
field_read<F: FromBytes>(&self, field: *const F) -> F247ad2907b4SAbdiel Janulgue     pub unsafe fn field_read<F: FromBytes>(&self, field: *const F) -> F {
248ad2907b4SAbdiel Janulgue         // SAFETY:
249ad2907b4SAbdiel Janulgue         // - By the safety requirements field is valid.
250ad2907b4SAbdiel Janulgue         // - Using read_volatile() here is not sound as per the usual rules, the usage here is
251ad2907b4SAbdiel Janulgue         // a special exception with the following notes in place. When dealing with a potential
252ad2907b4SAbdiel Janulgue         // race from a hardware or code outside kernel (e.g. user-space program), we need that
253ad2907b4SAbdiel Janulgue         // read on a valid memory is not UB. Currently read_volatile() is used for this, and the
254ad2907b4SAbdiel Janulgue         // rationale behind is that it should generate the same code as READ_ONCE() which the
255ad2907b4SAbdiel Janulgue         // kernel already relies on to avoid UB on data races. Note that the usage of
256ad2907b4SAbdiel Janulgue         // read_volatile() is limited to this particular case, it cannot be used to prevent
257ad2907b4SAbdiel Janulgue         // the UB caused by racing between two kernel functions nor do they provide atomicity.
258ad2907b4SAbdiel Janulgue         unsafe { field.read_volatile() }
259ad2907b4SAbdiel Janulgue     }
260ad2907b4SAbdiel Janulgue 
261ad2907b4SAbdiel Janulgue     /// Writes a value to `field` and ensures that its type is [`AsBytes`].
262ad2907b4SAbdiel Janulgue     ///
263ad2907b4SAbdiel Janulgue     /// # Safety
264ad2907b4SAbdiel Janulgue     ///
265ad2907b4SAbdiel Janulgue     /// This must be called from the [`dma_write`] macro which ensures that the `field` pointer is
266ad2907b4SAbdiel Janulgue     /// validated beforehand.
267ad2907b4SAbdiel Janulgue     ///
268ad2907b4SAbdiel Janulgue     /// Public but hidden since it should only be used from [`dma_write`] macro.
269ad2907b4SAbdiel Janulgue     #[doc(hidden)]
field_write<F: AsBytes>(&self, field: *mut F, val: F)270ad2907b4SAbdiel Janulgue     pub unsafe fn field_write<F: AsBytes>(&self, field: *mut F, val: F) {
271ad2907b4SAbdiel Janulgue         // SAFETY:
272ad2907b4SAbdiel Janulgue         // - By the safety requirements field is valid.
273ad2907b4SAbdiel Janulgue         // - Using write_volatile() here is not sound as per the usual rules, the usage here is
274ad2907b4SAbdiel Janulgue         // a special exception with the following notes in place. When dealing with a potential
275ad2907b4SAbdiel Janulgue         // race from a hardware or code outside kernel (e.g. user-space program), we need that
276ad2907b4SAbdiel Janulgue         // write on a valid memory is not UB. Currently write_volatile() is used for this, and the
277ad2907b4SAbdiel Janulgue         // rationale behind is that it should generate the same code as WRITE_ONCE() which the
278ad2907b4SAbdiel Janulgue         // kernel already relies on to avoid UB on data races. Note that the usage of
279ad2907b4SAbdiel Janulgue         // write_volatile() is limited to this particular case, it cannot be used to prevent
280ad2907b4SAbdiel Janulgue         // the UB caused by racing between two kernel functions nor do they provide atomicity.
281ad2907b4SAbdiel Janulgue         unsafe { field.write_volatile(val) }
282ad2907b4SAbdiel Janulgue     }
283ad2907b4SAbdiel Janulgue }
284ad2907b4SAbdiel Janulgue 
285ad2907b4SAbdiel Janulgue /// Note that the device configured to do DMA must be halted before this object is dropped.
286ad2907b4SAbdiel Janulgue impl<T: AsBytes + FromBytes> Drop for CoherentAllocation<T> {
drop(&mut self)287ad2907b4SAbdiel Janulgue     fn drop(&mut self) {
288ad2907b4SAbdiel Janulgue         let size = self.count * core::mem::size_of::<T>();
289ad2907b4SAbdiel Janulgue         // SAFETY: Device pointer is guaranteed as valid by the type invariant on `Device`.
290ad2907b4SAbdiel Janulgue         // The cpu address, and the dma handle are valid due to the type invariants on
291ad2907b4SAbdiel Janulgue         // `CoherentAllocation`.
292ad2907b4SAbdiel Janulgue         unsafe {
293ad2907b4SAbdiel Janulgue             bindings::dma_free_attrs(
294ad2907b4SAbdiel Janulgue                 self.dev.as_raw(),
295ad2907b4SAbdiel Janulgue                 size,
296ad2907b4SAbdiel Janulgue                 self.cpu_addr as _,
297ad2907b4SAbdiel Janulgue                 self.dma_handle,
298ad2907b4SAbdiel Janulgue                 self.dma_attrs.as_raw(),
299ad2907b4SAbdiel Janulgue             )
300ad2907b4SAbdiel Janulgue         }
301ad2907b4SAbdiel Janulgue     }
302ad2907b4SAbdiel Janulgue }
303ad2907b4SAbdiel Janulgue 
30428bb48c4SDanilo Krummrich // SAFETY: It is safe to send a `CoherentAllocation` to another thread if `T`
30528bb48c4SDanilo Krummrich // can be sent to another thread.
30628bb48c4SDanilo Krummrich unsafe impl<T: AsBytes + FromBytes + Send> Send for CoherentAllocation<T> {}
30728bb48c4SDanilo Krummrich 
308ad2907b4SAbdiel Janulgue /// Reads a field of an item from an allocated region of structs.
309ad2907b4SAbdiel Janulgue ///
310ad2907b4SAbdiel Janulgue /// # Examples
311ad2907b4SAbdiel Janulgue ///
312ad2907b4SAbdiel Janulgue /// ```
313ad2907b4SAbdiel Janulgue /// use kernel::device::Device;
314ad2907b4SAbdiel Janulgue /// use kernel::dma::{attrs::*, CoherentAllocation};
315ad2907b4SAbdiel Janulgue ///
316ad2907b4SAbdiel Janulgue /// struct MyStruct { field: u32, }
317ad2907b4SAbdiel Janulgue ///
318ad2907b4SAbdiel Janulgue /// // SAFETY: All bit patterns are acceptable values for `MyStruct`.
319ad2907b4SAbdiel Janulgue /// unsafe impl kernel::transmute::FromBytes for MyStruct{};
320ad2907b4SAbdiel Janulgue /// // SAFETY: Instances of `MyStruct` have no uninitialized portions.
321ad2907b4SAbdiel Janulgue /// unsafe impl kernel::transmute::AsBytes for MyStruct{};
322ad2907b4SAbdiel Janulgue ///
323ad2907b4SAbdiel Janulgue /// # fn test(alloc: &kernel::dma::CoherentAllocation<MyStruct>) -> Result {
324ad2907b4SAbdiel Janulgue /// let whole = kernel::dma_read!(alloc[2]);
325ad2907b4SAbdiel Janulgue /// let field = kernel::dma_read!(alloc[1].field);
326ad2907b4SAbdiel Janulgue /// # Ok::<(), Error>(()) }
327ad2907b4SAbdiel Janulgue /// ```
328ad2907b4SAbdiel Janulgue #[macro_export]
329ad2907b4SAbdiel Janulgue macro_rules! dma_read {
330ad2907b4SAbdiel Janulgue     ($dma:expr, $idx: expr, $($field:tt)*) => {{
331ad2907b4SAbdiel Janulgue         let item = $crate::dma::CoherentAllocation::item_from_index(&$dma, $idx)?;
332ad2907b4SAbdiel Janulgue         // SAFETY: `item_from_index` ensures that `item` is always a valid pointer and can be
333ad2907b4SAbdiel Janulgue         // dereferenced. The compiler also further validates the expression on whether `field`
334ad2907b4SAbdiel Janulgue         // is a member of `item` when expanded by the macro.
335ad2907b4SAbdiel Janulgue         unsafe {
336ad2907b4SAbdiel Janulgue             let ptr_field = ::core::ptr::addr_of!((*item) $($field)*);
337ad2907b4SAbdiel Janulgue             $crate::dma::CoherentAllocation::field_read(&$dma, ptr_field)
338ad2907b4SAbdiel Janulgue         }
339ad2907b4SAbdiel Janulgue     }};
340ad2907b4SAbdiel Janulgue     ($dma:ident [ $idx:expr ] $($field:tt)* ) => {
341ad2907b4SAbdiel Janulgue         $crate::dma_read!($dma, $idx, $($field)*);
342ad2907b4SAbdiel Janulgue     };
343ad2907b4SAbdiel Janulgue     ($($dma:ident).* [ $idx:expr ] $($field:tt)* ) => {
344ad2907b4SAbdiel Janulgue         $crate::dma_read!($($dma).*, $idx, $($field)*);
345ad2907b4SAbdiel Janulgue     };
346ad2907b4SAbdiel Janulgue }
347ad2907b4SAbdiel Janulgue 
348ad2907b4SAbdiel Janulgue /// Writes to a field of an item from an allocated region of structs.
349ad2907b4SAbdiel Janulgue ///
350ad2907b4SAbdiel Janulgue /// # Examples
351ad2907b4SAbdiel Janulgue ///
352ad2907b4SAbdiel Janulgue /// ```
353ad2907b4SAbdiel Janulgue /// use kernel::device::Device;
354ad2907b4SAbdiel Janulgue /// use kernel::dma::{attrs::*, CoherentAllocation};
355ad2907b4SAbdiel Janulgue ///
356ad2907b4SAbdiel Janulgue /// struct MyStruct { member: u32, }
357ad2907b4SAbdiel Janulgue ///
358ad2907b4SAbdiel Janulgue /// // SAFETY: All bit patterns are acceptable values for `MyStruct`.
359ad2907b4SAbdiel Janulgue /// unsafe impl kernel::transmute::FromBytes for MyStruct{};
360ad2907b4SAbdiel Janulgue /// // SAFETY: Instances of `MyStruct` have no uninitialized portions.
361ad2907b4SAbdiel Janulgue /// unsafe impl kernel::transmute::AsBytes for MyStruct{};
362ad2907b4SAbdiel Janulgue ///
363ad2907b4SAbdiel Janulgue /// # fn test(alloc: &kernel::dma::CoherentAllocation<MyStruct>) -> Result {
364ad2907b4SAbdiel Janulgue /// kernel::dma_write!(alloc[2].member = 0xf);
365ad2907b4SAbdiel Janulgue /// kernel::dma_write!(alloc[1] = MyStruct { member: 0xf });
366ad2907b4SAbdiel Janulgue /// # Ok::<(), Error>(()) }
367ad2907b4SAbdiel Janulgue /// ```
368ad2907b4SAbdiel Janulgue #[macro_export]
369ad2907b4SAbdiel Janulgue macro_rules! dma_write {
370ad2907b4SAbdiel Janulgue     ($dma:ident [ $idx:expr ] $($field:tt)*) => {{
371ad2907b4SAbdiel Janulgue         $crate::dma_write!($dma, $idx, $($field)*);
372ad2907b4SAbdiel Janulgue     }};
373ad2907b4SAbdiel Janulgue     ($($dma:ident).* [ $idx:expr ] $($field:tt)* ) => {{
374ad2907b4SAbdiel Janulgue         $crate::dma_write!($($dma).*, $idx, $($field)*);
375ad2907b4SAbdiel Janulgue     }};
376ad2907b4SAbdiel Janulgue     ($dma:expr, $idx: expr, = $val:expr) => {
377ad2907b4SAbdiel Janulgue         let item = $crate::dma::CoherentAllocation::item_from_index(&$dma, $idx)?;
378ad2907b4SAbdiel Janulgue         // SAFETY: `item_from_index` ensures that `item` is always a valid item.
379ad2907b4SAbdiel Janulgue         unsafe { $crate::dma::CoherentAllocation::field_write(&$dma, item, $val) }
380ad2907b4SAbdiel Janulgue     };
381ad2907b4SAbdiel Janulgue     ($dma:expr, $idx: expr, $(.$field:ident)* = $val:expr) => {
382ad2907b4SAbdiel Janulgue         let item = $crate::dma::CoherentAllocation::item_from_index(&$dma, $idx)?;
383ad2907b4SAbdiel Janulgue         // SAFETY: `item_from_index` ensures that `item` is always a valid pointer and can be
384ad2907b4SAbdiel Janulgue         // dereferenced. The compiler also further validates the expression on whether `field`
385ad2907b4SAbdiel Janulgue         // is a member of `item` when expanded by the macro.
386ad2907b4SAbdiel Janulgue         unsafe {
387ad2907b4SAbdiel Janulgue             let ptr_field = ::core::ptr::addr_of_mut!((*item) $(.$field)*);
388ad2907b4SAbdiel Janulgue             $crate::dma::CoherentAllocation::field_write(&$dma, ptr_field, $val)
389ad2907b4SAbdiel Janulgue         }
390ad2907b4SAbdiel Janulgue     };
391ad2907b4SAbdiel Janulgue }
392