kernel/dma.rs
1// SPDX-License-Identifier: GPL-2.0
2
3//! Direct memory access (DMA).
4//!
5//! C header: [`include/linux/dma-mapping.h`](srctree/include/linux/dma-mapping.h)
6
7use crate::{
8 bindings, build_assert, device,
9 device::{Bound, Core},
10 error::{to_result, Result},
11 prelude::*,
12 sync::aref::ARef,
13 transmute::{AsBytes, FromBytes},
14};
15use core::ptr::NonNull;
16
17/// DMA address type.
18///
19/// Represents a bus address used for Direct Memory Access (DMA) operations.
20///
21/// This is an alias of the kernel's `dma_addr_t`, which may be `u32` or `u64` depending on
22/// `CONFIG_ARCH_DMA_ADDR_T_64BIT`.
23///
24/// Note that this may be `u64` even on 32-bit architectures.
25pub type DmaAddress = bindings::dma_addr_t;
26
27/// Trait to be implemented by DMA capable bus devices.
28///
29/// The [`dma::Device`](Device) trait should be implemented by bus specific device representations,
30/// where the underlying bus is DMA capable, such as:
31#[cfg_attr(CONFIG_PCI, doc = "* [`pci::Device`](kernel::pci::Device)")]
32/// * [`platform::Device`](::kernel::platform::Device)
33pub trait Device: AsRef<device::Device<Core>> {
34 /// Set up the device's DMA streaming addressing capabilities.
35 ///
36 /// This method is usually called once from `probe()` as soon as the device capabilities are
37 /// known.
38 ///
39 /// # Safety
40 ///
41 /// This method must not be called concurrently with any DMA allocation or mapping primitives,
42 /// such as [`CoherentAllocation::alloc_attrs`].
43 unsafe fn dma_set_mask(&self, mask: DmaMask) -> Result {
44 // SAFETY:
45 // - By the type invariant of `device::Device`, `self.as_ref().as_raw()` is valid.
46 // - The safety requirement of this function guarantees that there are no concurrent calls
47 // to DMA allocation and mapping primitives using this mask.
48 to_result(unsafe { bindings::dma_set_mask(self.as_ref().as_raw(), mask.value()) })
49 }
50
51 /// Set up the device's DMA coherent addressing capabilities.
52 ///
53 /// This method is usually called once from `probe()` as soon as the device capabilities are
54 /// known.
55 ///
56 /// # Safety
57 ///
58 /// This method must not be called concurrently with any DMA allocation or mapping primitives,
59 /// such as [`CoherentAllocation::alloc_attrs`].
60 unsafe fn dma_set_coherent_mask(&self, mask: DmaMask) -> Result {
61 // SAFETY:
62 // - By the type invariant of `device::Device`, `self.as_ref().as_raw()` is valid.
63 // - The safety requirement of this function guarantees that there are no concurrent calls
64 // to DMA allocation and mapping primitives using this mask.
65 to_result(unsafe { bindings::dma_set_coherent_mask(self.as_ref().as_raw(), mask.value()) })
66 }
67
68 /// Set up the device's DMA addressing capabilities.
69 ///
70 /// This is a combination of [`Device::dma_set_mask`] and [`Device::dma_set_coherent_mask`].
71 ///
72 /// This method is usually called once from `probe()` as soon as the device capabilities are
73 /// known.
74 ///
75 /// # Safety
76 ///
77 /// This method must not be called concurrently with any DMA allocation or mapping primitives,
78 /// such as [`CoherentAllocation::alloc_attrs`].
79 unsafe fn dma_set_mask_and_coherent(&self, mask: DmaMask) -> Result {
80 // SAFETY:
81 // - By the type invariant of `device::Device`, `self.as_ref().as_raw()` is valid.
82 // - The safety requirement of this function guarantees that there are no concurrent calls
83 // to DMA allocation and mapping primitives using this mask.
84 to_result(unsafe {
85 bindings::dma_set_mask_and_coherent(self.as_ref().as_raw(), mask.value())
86 })
87 }
88}
89
90/// A DMA mask that holds a bitmask with the lowest `n` bits set.
91///
92/// Use [`DmaMask::new`] or [`DmaMask::try_new`] to construct a value. Values
93/// are guaranteed to never exceed the bit width of `u64`.
94///
95/// This is the Rust equivalent of the C macro `DMA_BIT_MASK()`.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub struct DmaMask(u64);
98
99impl DmaMask {
100 /// Constructs a `DmaMask` with the lowest `n` bits set to `1`.
101 ///
102 /// For `n <= 64`, sets exactly the lowest `n` bits.
103 /// For `n > 64`, results in a build error.
104 ///
105 /// # Examples
106 ///
107 /// ```
108 /// use kernel::dma::DmaMask;
109 ///
110 /// let mask0 = DmaMask::new::<0>();
111 /// assert_eq!(mask0.value(), 0);
112 ///
113 /// let mask1 = DmaMask::new::<1>();
114 /// assert_eq!(mask1.value(), 0b1);
115 ///
116 /// let mask64 = DmaMask::new::<64>();
117 /// assert_eq!(mask64.value(), u64::MAX);
118 ///
119 /// // Build failure.
120 /// // let mask_overflow = DmaMask::new::<100>();
121 /// ```
122 #[inline]
123 pub const fn new<const N: u32>() -> Self {
124 let Ok(mask) = Self::try_new(N) else {
125 build_error!("Invalid DMA Mask.");
126 };
127
128 mask
129 }
130
131 /// Constructs a `DmaMask` with the lowest `n` bits set to `1`.
132 ///
133 /// For `n <= 64`, sets exactly the lowest `n` bits.
134 /// For `n > 64`, returns [`EINVAL`].
135 ///
136 /// # Examples
137 ///
138 /// ```
139 /// use kernel::dma::DmaMask;
140 ///
141 /// let mask0 = DmaMask::try_new(0)?;
142 /// assert_eq!(mask0.value(), 0);
143 ///
144 /// let mask1 = DmaMask::try_new(1)?;
145 /// assert_eq!(mask1.value(), 0b1);
146 ///
147 /// let mask64 = DmaMask::try_new(64)?;
148 /// assert_eq!(mask64.value(), u64::MAX);
149 ///
150 /// let mask_overflow = DmaMask::try_new(100);
151 /// assert!(mask_overflow.is_err());
152 /// # Ok::<(), Error>(())
153 /// ```
154 #[inline]
155 pub const fn try_new(n: u32) -> Result<Self> {
156 Ok(Self(match n {
157 0 => 0,
158 1..=64 => u64::MAX >> (64 - n),
159 _ => return Err(EINVAL),
160 }))
161 }
162
163 /// Returns the underlying `u64` bitmask value.
164 #[inline]
165 pub const fn value(&self) -> u64 {
166 self.0
167 }
168}
169
170/// Possible attributes associated with a DMA mapping.
171///
172/// They can be combined with the operators `|`, `&`, and `!`.
173///
174/// Values can be used from the [`attrs`] module.
175///
176/// # Examples
177///
178/// ```
179/// # use kernel::device::{Bound, Device};
180/// use kernel::dma::{attrs::*, CoherentAllocation};
181///
182/// # fn test(dev: &Device<Bound>) -> Result {
183/// let attribs = DMA_ATTR_FORCE_CONTIGUOUS | DMA_ATTR_NO_WARN;
184/// let c: CoherentAllocation<u64> =
185/// CoherentAllocation::alloc_attrs(dev, 4, GFP_KERNEL, attribs)?;
186/// # Ok::<(), Error>(()) }
187/// ```
188#[derive(Clone, Copy, PartialEq)]
189#[repr(transparent)]
190pub struct Attrs(u32);
191
192impl Attrs {
193 /// Get the raw representation of this attribute.
194 pub(crate) fn as_raw(self) -> crate::ffi::c_ulong {
195 self.0 as crate::ffi::c_ulong
196 }
197
198 /// Check whether `flags` is contained in `self`.
199 pub fn contains(self, flags: Attrs) -> bool {
200 (self & flags) == flags
201 }
202}
203
204impl core::ops::BitOr for Attrs {
205 type Output = Self;
206 fn bitor(self, rhs: Self) -> Self::Output {
207 Self(self.0 | rhs.0)
208 }
209}
210
211impl core::ops::BitAnd for Attrs {
212 type Output = Self;
213 fn bitand(self, rhs: Self) -> Self::Output {
214 Self(self.0 & rhs.0)
215 }
216}
217
218impl core::ops::Not for Attrs {
219 type Output = Self;
220 fn not(self) -> Self::Output {
221 Self(!self.0)
222 }
223}
224
225/// DMA mapping attributes.
226pub mod attrs {
227 use super::Attrs;
228
229 /// Specifies that reads and writes to the mapping may be weakly ordered, that is that reads
230 /// and writes may pass each other.
231 pub const DMA_ATTR_WEAK_ORDERING: Attrs = Attrs(bindings::DMA_ATTR_WEAK_ORDERING);
232
233 /// Specifies that writes to the mapping may be buffered to improve performance.
234 pub const DMA_ATTR_WRITE_COMBINE: Attrs = Attrs(bindings::DMA_ATTR_WRITE_COMBINE);
235
236 /// Lets the platform to avoid creating a kernel virtual mapping for the allocated buffer.
237 pub const DMA_ATTR_NO_KERNEL_MAPPING: Attrs = Attrs(bindings::DMA_ATTR_NO_KERNEL_MAPPING);
238
239 /// Allows platform code to skip synchronization of the CPU cache for the given buffer assuming
240 /// that it has been already transferred to 'device' domain.
241 pub const DMA_ATTR_SKIP_CPU_SYNC: Attrs = Attrs(bindings::DMA_ATTR_SKIP_CPU_SYNC);
242
243 /// Forces contiguous allocation of the buffer in physical memory.
244 pub const DMA_ATTR_FORCE_CONTIGUOUS: Attrs = Attrs(bindings::DMA_ATTR_FORCE_CONTIGUOUS);
245
246 /// Hints DMA-mapping subsystem that it's probably not worth the time to try
247 /// to allocate memory to in a way that gives better TLB efficiency.
248 pub const DMA_ATTR_ALLOC_SINGLE_PAGES: Attrs = Attrs(bindings::DMA_ATTR_ALLOC_SINGLE_PAGES);
249
250 /// This tells the DMA-mapping subsystem to suppress allocation failure reports (similarly to
251 /// `__GFP_NOWARN`).
252 pub const DMA_ATTR_NO_WARN: Attrs = Attrs(bindings::DMA_ATTR_NO_WARN);
253
254 /// Indicates that the buffer is fully accessible at an elevated privilege level (and
255 /// ideally inaccessible or at least read-only at lesser-privileged levels).
256 pub const DMA_ATTR_PRIVILEGED: Attrs = Attrs(bindings::DMA_ATTR_PRIVILEGED);
257
258 /// Indicates that the buffer is MMIO memory.
259 pub const DMA_ATTR_MMIO: Attrs = Attrs(bindings::DMA_ATTR_MMIO);
260}
261
262/// DMA data direction.
263///
264/// Corresponds to the C [`enum dma_data_direction`].
265///
266/// [`enum dma_data_direction`]: srctree/include/linux/dma-direction.h
267#[derive(Copy, Clone, PartialEq, Eq, Debug)]
268#[repr(u32)]
269pub enum DataDirection {
270 /// The DMA mapping is for bidirectional data transfer.
271 ///
272 /// This is used when the buffer can be both read from and written to by the device.
273 /// The cache for the corresponding memory region is both flushed and invalidated.
274 Bidirectional = Self::const_cast(bindings::dma_data_direction_DMA_BIDIRECTIONAL),
275
276 /// The DMA mapping is for data transfer from memory to the device (write).
277 ///
278 /// The CPU has prepared data in the buffer, and the device will read it.
279 /// The cache for the corresponding memory region is flushed before device access.
280 ToDevice = Self::const_cast(bindings::dma_data_direction_DMA_TO_DEVICE),
281
282 /// The DMA mapping is for data transfer from the device to memory (read).
283 ///
284 /// The device will write data into the buffer for the CPU to read.
285 /// The cache for the corresponding memory region is invalidated before CPU access.
286 FromDevice = Self::const_cast(bindings::dma_data_direction_DMA_FROM_DEVICE),
287
288 /// The DMA mapping is not for data transfer.
289 ///
290 /// This is primarily for debugging purposes. With this direction, the DMA mapping API
291 /// will not perform any cache coherency operations.
292 None = Self::const_cast(bindings::dma_data_direction_DMA_NONE),
293}
294
295impl DataDirection {
296 /// Casts the bindgen-generated enum type to a `u32` at compile time.
297 ///
298 /// This function will cause a compile-time error if the underlying value of the
299 /// C enum is out of bounds for `u32`.
300 const fn const_cast(val: bindings::dma_data_direction) -> u32 {
301 // CAST: The C standard allows compilers to choose different integer types for enums.
302 // To safely check the value, we cast it to a wide signed integer type (`i128`)
303 // which can hold any standard C integer enum type without truncation.
304 let wide_val = val as i128;
305
306 // Check if the value is outside the valid range for the target type `u32`.
307 // CAST: `u32::MAX` is cast to `i128` to match the type of `wide_val` for the comparison.
308 if wide_val < 0 || wide_val > u32::MAX as i128 {
309 // Trigger a compile-time error in a const context.
310 build_error!("C enum value is out of bounds for the target type `u32`.");
311 }
312
313 // CAST: This cast is valid because the check above guarantees that `wide_val`
314 // is within the representable range of `u32`.
315 wide_val as u32
316 }
317}
318
319impl From<DataDirection> for bindings::dma_data_direction {
320 /// Returns the raw representation of [`enum dma_data_direction`].
321 fn from(direction: DataDirection) -> Self {
322 // CAST: `direction as u32` gets the underlying representation of our `#[repr(u32)]` enum.
323 // The subsequent cast to `Self` (the bindgen type) assumes the C enum is compatible
324 // with the enum variants of `DataDirection`, which is a valid assumption given our
325 // compile-time checks.
326 direction as u32 as Self
327 }
328}
329
330/// An abstraction of the `dma_alloc_coherent` API.
331///
332/// This is an abstraction around the `dma_alloc_coherent` API which is used to allocate and map
333/// large coherent DMA regions.
334///
335/// A [`CoherentAllocation`] instance contains a pointer to the allocated region (in the
336/// processor's virtual address space) and the device address which can be given to the device
337/// as the DMA address base of the region. The region is released once [`CoherentAllocation`]
338/// is dropped.
339///
340/// # Invariants
341///
342/// - For the lifetime of an instance of [`CoherentAllocation`], the `cpu_addr` is a valid pointer
343/// to an allocated region of coherent memory and `dma_handle` is the DMA address base of the
344/// region.
345/// - The size in bytes of the allocation is equal to `size_of::<T> * count`.
346/// - `size_of::<T> * count` fits into a `usize`.
347// TODO
348//
349// DMA allocations potentially carry device resources (e.g.IOMMU mappings), hence for soundness
350// reasons DMA allocation would need to be embedded in a `Devres` container, in order to ensure
351// that device resources can never survive device unbind.
352//
353// However, it is neither desirable nor necessary to protect the allocated memory of the DMA
354// allocation from surviving device unbind; it would require RCU read side critical sections to
355// access the memory, which may require subsequent unnecessary copies.
356//
357// Hence, find a way to revoke the device resources of a `CoherentAllocation`, but not the
358// entire `CoherentAllocation` including the allocated memory itself.
359pub struct CoherentAllocation<T: AsBytes + FromBytes> {
360 dev: ARef<device::Device>,
361 dma_handle: DmaAddress,
362 count: usize,
363 cpu_addr: NonNull<T>,
364 dma_attrs: Attrs,
365}
366
367impl<T: AsBytes + FromBytes> CoherentAllocation<T> {
368 /// Allocates a region of `size_of::<T> * count` of coherent memory.
369 ///
370 /// # Examples
371 ///
372 /// ```
373 /// # use kernel::device::{Bound, Device};
374 /// use kernel::dma::{attrs::*, CoherentAllocation};
375 ///
376 /// # fn test(dev: &Device<Bound>) -> Result {
377 /// let c: CoherentAllocation<u64> =
378 /// CoherentAllocation::alloc_attrs(dev, 4, GFP_KERNEL, DMA_ATTR_NO_WARN)?;
379 /// # Ok::<(), Error>(()) }
380 /// ```
381 pub fn alloc_attrs(
382 dev: &device::Device<Bound>,
383 count: usize,
384 gfp_flags: kernel::alloc::Flags,
385 dma_attrs: Attrs,
386 ) -> Result<CoherentAllocation<T>> {
387 build_assert!(
388 core::mem::size_of::<T>() > 0,
389 "It doesn't make sense for the allocated type to be a ZST"
390 );
391
392 let size = count
393 .checked_mul(core::mem::size_of::<T>())
394 .ok_or(EOVERFLOW)?;
395 let mut dma_handle = 0;
396 // SAFETY: Device pointer is guaranteed as valid by the type invariant on `Device`.
397 let addr = unsafe {
398 bindings::dma_alloc_attrs(
399 dev.as_raw(),
400 size,
401 &mut dma_handle,
402 gfp_flags.as_raw(),
403 dma_attrs.as_raw(),
404 )
405 };
406 let addr = NonNull::new(addr).ok_or(ENOMEM)?;
407 // INVARIANT:
408 // - We just successfully allocated a coherent region which is accessible for
409 // `count` elements, hence the cpu address is valid. We also hold a refcounted reference
410 // to the device.
411 // - The allocated `size` is equal to `size_of::<T> * count`.
412 // - The allocated `size` fits into a `usize`.
413 Ok(Self {
414 dev: dev.into(),
415 dma_handle,
416 count,
417 cpu_addr: addr.cast(),
418 dma_attrs,
419 })
420 }
421
422 /// Performs the same functionality as [`CoherentAllocation::alloc_attrs`], except the
423 /// `dma_attrs` is 0 by default.
424 pub fn alloc_coherent(
425 dev: &device::Device<Bound>,
426 count: usize,
427 gfp_flags: kernel::alloc::Flags,
428 ) -> Result<CoherentAllocation<T>> {
429 CoherentAllocation::alloc_attrs(dev, count, gfp_flags, Attrs(0))
430 }
431
432 /// Returns the number of elements `T` in this allocation.
433 ///
434 /// Note that this is not the size of the allocation in bytes, which is provided by
435 /// [`Self::size`].
436 pub fn count(&self) -> usize {
437 self.count
438 }
439
440 /// Returns the size in bytes of this allocation.
441 pub fn size(&self) -> usize {
442 // INVARIANT: The type invariant of `Self` guarantees that `size_of::<T> * count` fits into
443 // a `usize`.
444 self.count * core::mem::size_of::<T>()
445 }
446
447 /// Returns the base address to the allocated region in the CPU's virtual address space.
448 pub fn start_ptr(&self) -> *const T {
449 self.cpu_addr.as_ptr()
450 }
451
452 /// Returns the base address to the allocated region in the CPU's virtual address space as
453 /// a mutable pointer.
454 pub fn start_ptr_mut(&mut self) -> *mut T {
455 self.cpu_addr.as_ptr()
456 }
457
458 /// Returns a DMA handle which may be given to the device as the DMA address base of
459 /// the region.
460 pub fn dma_handle(&self) -> DmaAddress {
461 self.dma_handle
462 }
463
464 /// Returns a DMA handle starting at `offset` (in units of `T`) which may be given to the
465 /// device as the DMA address base of the region.
466 ///
467 /// Returns `EINVAL` if `offset` is not within the bounds of the allocation.
468 pub fn dma_handle_with_offset(&self, offset: usize) -> Result<DmaAddress> {
469 if offset >= self.count {
470 Err(EINVAL)
471 } else {
472 // INVARIANT: The type invariant of `Self` guarantees that `size_of::<T> * count` fits
473 // into a `usize`, and `offset` is inferior to `count`.
474 Ok(self.dma_handle + (offset * core::mem::size_of::<T>()) as DmaAddress)
475 }
476 }
477
478 /// Common helper to validate a range applied from the allocated region in the CPU's virtual
479 /// address space.
480 fn validate_range(&self, offset: usize, count: usize) -> Result {
481 if offset.checked_add(count).ok_or(EOVERFLOW)? > self.count {
482 return Err(EINVAL);
483 }
484 Ok(())
485 }
486
487 /// Returns the data from the region starting from `offset` as a slice.
488 /// `offset` and `count` are in units of `T`, not the number of bytes.
489 ///
490 /// For ringbuffer type of r/w access or use-cases where the pointer to the live data is needed,
491 /// [`CoherentAllocation::start_ptr`] or [`CoherentAllocation::start_ptr_mut`] could be used
492 /// instead.
493 ///
494 /// # Safety
495 ///
496 /// * Callers must ensure that the device does not read/write to/from memory while the returned
497 /// slice is live.
498 /// * Callers must ensure that this call does not race with a write to the same region while
499 /// the returned slice is live.
500 pub unsafe fn as_slice(&self, offset: usize, count: usize) -> Result<&[T]> {
501 self.validate_range(offset, count)?;
502 // SAFETY:
503 // - The pointer is valid due to type invariant on `CoherentAllocation`,
504 // we've just checked that the range and index is within bounds. The immutability of the
505 // data is also guaranteed by the safety requirements of the function.
506 // - `offset + count` can't overflow since it is smaller than `self.count` and we've checked
507 // that `self.count` won't overflow early in the constructor.
508 Ok(unsafe { core::slice::from_raw_parts(self.start_ptr().add(offset), count) })
509 }
510
511 /// Performs the same functionality as [`CoherentAllocation::as_slice`], except that a mutable
512 /// slice is returned.
513 ///
514 /// # Safety
515 ///
516 /// * Callers must ensure that the device does not read/write to/from memory while the returned
517 /// slice is live.
518 /// * Callers must ensure that this call does not race with a read or write to the same region
519 /// while the returned slice is live.
520 pub unsafe fn as_slice_mut(&mut self, offset: usize, count: usize) -> Result<&mut [T]> {
521 self.validate_range(offset, count)?;
522 // SAFETY:
523 // - The pointer is valid due to type invariant on `CoherentAllocation`,
524 // we've just checked that the range and index is within bounds. The immutability of the
525 // data is also guaranteed by the safety requirements of the function.
526 // - `offset + count` can't overflow since it is smaller than `self.count` and we've checked
527 // that `self.count` won't overflow early in the constructor.
528 Ok(unsafe { core::slice::from_raw_parts_mut(self.start_ptr_mut().add(offset), count) })
529 }
530
531 /// Writes data to the region starting from `offset`. `offset` is in units of `T`, not the
532 /// number of bytes.
533 ///
534 /// # Safety
535 ///
536 /// * Callers must ensure that this call does not race with a read or write to the same region
537 /// that overlaps with this write.
538 ///
539 /// # Examples
540 ///
541 /// ```
542 /// # fn test(alloc: &mut kernel::dma::CoherentAllocation<u8>) -> Result {
543 /// let somedata: [u8; 4] = [0xf; 4];
544 /// let buf: &[u8] = &somedata;
545 /// // SAFETY: There is no concurrent HW operation on the device and no other R/W access to the
546 /// // region.
547 /// unsafe { alloc.write(buf, 0)?; }
548 /// # Ok::<(), Error>(()) }
549 /// ```
550 pub unsafe fn write(&mut self, src: &[T], offset: usize) -> Result {
551 self.validate_range(offset, src.len())?;
552 // SAFETY:
553 // - The pointer is valid due to type invariant on `CoherentAllocation`
554 // and we've just checked that the range and index is within bounds.
555 // - `offset + count` can't overflow since it is smaller than `self.count` and we've checked
556 // that `self.count` won't overflow early in the constructor.
557 unsafe {
558 core::ptr::copy_nonoverlapping(
559 src.as_ptr(),
560 self.start_ptr_mut().add(offset),
561 src.len(),
562 )
563 };
564 Ok(())
565 }
566
567 /// Returns a pointer to an element from the region with bounds checking. `offset` is in
568 /// units of `T`, not the number of bytes.
569 ///
570 /// Public but hidden since it should only be used from [`dma_read`] and [`dma_write`] macros.
571 #[doc(hidden)]
572 pub fn item_from_index(&self, offset: usize) -> Result<*mut T> {
573 if offset >= self.count {
574 return Err(EINVAL);
575 }
576 // SAFETY:
577 // - The pointer is valid due to type invariant on `CoherentAllocation`
578 // and we've just checked that the range and index is within bounds.
579 // - `offset` can't overflow since it is smaller than `self.count` and we've checked
580 // that `self.count` won't overflow early in the constructor.
581 Ok(unsafe { self.cpu_addr.as_ptr().add(offset) })
582 }
583
584 /// Reads the value of `field` and ensures that its type is [`FromBytes`].
585 ///
586 /// # Safety
587 ///
588 /// This must be called from the [`dma_read`] macro which ensures that the `field` pointer is
589 /// validated beforehand.
590 ///
591 /// Public but hidden since it should only be used from [`dma_read`] macro.
592 #[doc(hidden)]
593 pub unsafe fn field_read<F: FromBytes>(&self, field: *const F) -> F {
594 // SAFETY:
595 // - By the safety requirements field is valid.
596 // - Using read_volatile() here is not sound as per the usual rules, the usage here is
597 // a special exception with the following notes in place. When dealing with a potential
598 // race from a hardware or code outside kernel (e.g. user-space program), we need that
599 // read on a valid memory is not UB. Currently read_volatile() is used for this, and the
600 // rationale behind is that it should generate the same code as READ_ONCE() which the
601 // kernel already relies on to avoid UB on data races. Note that the usage of
602 // read_volatile() is limited to this particular case, it cannot be used to prevent
603 // the UB caused by racing between two kernel functions nor do they provide atomicity.
604 unsafe { field.read_volatile() }
605 }
606
607 /// Writes a value to `field` and ensures that its type is [`AsBytes`].
608 ///
609 /// # Safety
610 ///
611 /// This must be called from the [`dma_write`] macro which ensures that the `field` pointer is
612 /// validated beforehand.
613 ///
614 /// Public but hidden since it should only be used from [`dma_write`] macro.
615 #[doc(hidden)]
616 pub unsafe fn field_write<F: AsBytes>(&self, field: *mut F, val: F) {
617 // SAFETY:
618 // - By the safety requirements field is valid.
619 // - Using write_volatile() here is not sound as per the usual rules, the usage here is
620 // a special exception with the following notes in place. When dealing with a potential
621 // race from a hardware or code outside kernel (e.g. user-space program), we need that
622 // write on a valid memory is not UB. Currently write_volatile() is used for this, and the
623 // rationale behind is that it should generate the same code as WRITE_ONCE() which the
624 // kernel already relies on to avoid UB on data races. Note that the usage of
625 // write_volatile() is limited to this particular case, it cannot be used to prevent
626 // the UB caused by racing between two kernel functions nor do they provide atomicity.
627 unsafe { field.write_volatile(val) }
628 }
629}
630
631/// Note that the device configured to do DMA must be halted before this object is dropped.
632impl<T: AsBytes + FromBytes> Drop for CoherentAllocation<T> {
633 fn drop(&mut self) {
634 let size = self.count * core::mem::size_of::<T>();
635 // SAFETY: Device pointer is guaranteed as valid by the type invariant on `Device`.
636 // The cpu address, and the dma handle are valid due to the type invariants on
637 // `CoherentAllocation`.
638 unsafe {
639 bindings::dma_free_attrs(
640 self.dev.as_raw(),
641 size,
642 self.start_ptr_mut().cast(),
643 self.dma_handle,
644 self.dma_attrs.as_raw(),
645 )
646 }
647 }
648}
649
650// SAFETY: It is safe to send a `CoherentAllocation` to another thread if `T`
651// can be sent to another thread.
652unsafe impl<T: AsBytes + FromBytes + Send> Send for CoherentAllocation<T> {}
653
654/// Reads a field of an item from an allocated region of structs.
655///
656/// # Examples
657///
658/// ```
659/// use kernel::device::Device;
660/// use kernel::dma::{attrs::*, CoherentAllocation};
661///
662/// struct MyStruct { field: u32, }
663///
664/// // SAFETY: All bit patterns are acceptable values for `MyStruct`.
665/// unsafe impl kernel::transmute::FromBytes for MyStruct{};
666/// // SAFETY: Instances of `MyStruct` have no uninitialized portions.
667/// unsafe impl kernel::transmute::AsBytes for MyStruct{};
668///
669/// # fn test(alloc: &kernel::dma::CoherentAllocation<MyStruct>) -> Result {
670/// let whole = kernel::dma_read!(alloc[2]);
671/// let field = kernel::dma_read!(alloc[1].field);
672/// # Ok::<(), Error>(()) }
673/// ```
674#[macro_export]
675macro_rules! dma_read {
676 ($dma:expr, $idx: expr, $($field:tt)*) => {{
677 (|| -> ::core::result::Result<_, $crate::error::Error> {
678 let item = $crate::dma::CoherentAllocation::item_from_index(&$dma, $idx)?;
679 // SAFETY: `item_from_index` ensures that `item` is always a valid pointer and can be
680 // dereferenced. The compiler also further validates the expression on whether `field`
681 // is a member of `item` when expanded by the macro.
682 unsafe {
683 let ptr_field = ::core::ptr::addr_of!((*item) $($field)*);
684 ::core::result::Result::Ok(
685 $crate::dma::CoherentAllocation::field_read(&$dma, ptr_field)
686 )
687 }
688 })()
689 }};
690 ($dma:ident [ $idx:expr ] $($field:tt)* ) => {
691 $crate::dma_read!($dma, $idx, $($field)*)
692 };
693 ($($dma:ident).* [ $idx:expr ] $($field:tt)* ) => {
694 $crate::dma_read!($($dma).*, $idx, $($field)*)
695 };
696}
697
698/// Writes to a field of an item from an allocated region of structs.
699///
700/// # Examples
701///
702/// ```
703/// use kernel::device::Device;
704/// use kernel::dma::{attrs::*, CoherentAllocation};
705///
706/// struct MyStruct { member: u32, }
707///
708/// // SAFETY: All bit patterns are acceptable values for `MyStruct`.
709/// unsafe impl kernel::transmute::FromBytes for MyStruct{};
710/// // SAFETY: Instances of `MyStruct` have no uninitialized portions.
711/// unsafe impl kernel::transmute::AsBytes for MyStruct{};
712///
713/// # fn test(alloc: &kernel::dma::CoherentAllocation<MyStruct>) -> Result {
714/// kernel::dma_write!(alloc[2].member = 0xf);
715/// kernel::dma_write!(alloc[1] = MyStruct { member: 0xf });
716/// # Ok::<(), Error>(()) }
717/// ```
718#[macro_export]
719macro_rules! dma_write {
720 ($dma:ident [ $idx:expr ] $($field:tt)*) => {{
721 $crate::dma_write!($dma, $idx, $($field)*)
722 }};
723 ($($dma:ident).* [ $idx:expr ] $($field:tt)* ) => {{
724 $crate::dma_write!($($dma).*, $idx, $($field)*)
725 }};
726 ($dma:expr, $idx: expr, = $val:expr) => {
727 (|| -> ::core::result::Result<_, $crate::error::Error> {
728 let item = $crate::dma::CoherentAllocation::item_from_index(&$dma, $idx)?;
729 // SAFETY: `item_from_index` ensures that `item` is always a valid item.
730 unsafe { $crate::dma::CoherentAllocation::field_write(&$dma, item, $val) }
731 ::core::result::Result::Ok(())
732 })()
733 };
734 ($dma:expr, $idx: expr, $(.$field:ident)* = $val:expr) => {
735 (|| -> ::core::result::Result<_, $crate::error::Error> {
736 let item = $crate::dma::CoherentAllocation::item_from_index(&$dma, $idx)?;
737 // SAFETY: `item_from_index` ensures that `item` is always a valid pointer and can be
738 // dereferenced. The compiler also further validates the expression on whether `field`
739 // is a member of `item` when expanded by the macro.
740 unsafe {
741 let ptr_field = ::core::ptr::addr_of_mut!((*item) $(.$field)*);
742 $crate::dma::CoherentAllocation::field_write(&$dma, ptr_field, $val)
743 }
744 ::core::result::Result::Ok(())
745 })()
746 };
747}