Skip to main content

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,
9    debugfs,
10    device::{
11        self,
12        Bound,
13        Core, //
14    },
15    error::to_result,
16    fs::file,
17    io::{
18        IoBackend,
19        IoBase,
20        IoCapable,
21        IoCopyable,
22        SysMem,
23        SysMemBackend, //
24    },
25    prelude::*,
26    ptr::KnownSize,
27    transmute::{
28        AsBytes,
29        FromBytes, //
30    },
31    uaccess::UserSliceWriter, //
32};
33use core::{
34    ops::{
35        Deref,
36        DerefMut, //
37    },
38    ptr::NonNull, //
39};
40
41/// DMA address type.
42///
43/// Represents a bus address used for Direct Memory Access (DMA) operations.
44///
45/// This is an alias of the kernel's `dma_addr_t`, which may be `u32` or `u64` depending on
46/// `CONFIG_ARCH_DMA_ADDR_T_64BIT`.
47///
48/// Note that this may be `u64` even on 32-bit architectures.
49pub type DmaAddress = bindings::dma_addr_t;
50
51/// Trait to be implemented by DMA capable bus devices.
52///
53/// The [`dma::Device`](Device) trait should be implemented by bus specific device representations,
54/// where the underlying bus is DMA capable, such as:
55#[cfg_attr(CONFIG_PCI, doc = "* [`pci::Device`](kernel::pci::Device)")]
56/// * [`platform::Device`](::kernel::platform::Device)
57pub trait Device<'a>: AsRef<device::Device<Core<'a>>> {
58    /// Set up the device's DMA streaming addressing capabilities.
59    ///
60    /// This method is usually called once from `probe()` as soon as the device capabilities are
61    /// known.
62    ///
63    /// # Safety
64    ///
65    /// This method must not be called concurrently with any DMA allocation or mapping primitives,
66    /// such as [`Coherent::zeroed`].
67    unsafe fn dma_set_mask(&self, mask: DmaMask) -> Result {
68        // SAFETY:
69        // - By the type invariant of `device::Device`, `self.as_ref().as_raw()` is valid.
70        // - The safety requirement of this function guarantees that there are no concurrent calls
71        //   to DMA allocation and mapping primitives using this mask.
72        to_result(unsafe { bindings::dma_set_mask(self.as_ref().as_raw(), mask.value()) })
73    }
74
75    /// Set up the device's DMA coherent addressing capabilities.
76    ///
77    /// This method is usually called once from `probe()` as soon as the device capabilities are
78    /// known.
79    ///
80    /// # Safety
81    ///
82    /// This method must not be called concurrently with any DMA allocation or mapping primitives,
83    /// such as [`Coherent::zeroed`].
84    unsafe fn dma_set_coherent_mask(&self, mask: DmaMask) -> Result {
85        // SAFETY:
86        // - By the type invariant of `device::Device`, `self.as_ref().as_raw()` is valid.
87        // - The safety requirement of this function guarantees that there are no concurrent calls
88        //   to DMA allocation and mapping primitives using this mask.
89        to_result(unsafe { bindings::dma_set_coherent_mask(self.as_ref().as_raw(), mask.value()) })
90    }
91
92    /// Set up the device's DMA addressing capabilities.
93    ///
94    /// This is a combination of [`Device::dma_set_mask`] and [`Device::dma_set_coherent_mask`].
95    ///
96    /// This method is usually called once from `probe()` as soon as the device capabilities are
97    /// known.
98    ///
99    /// # Safety
100    ///
101    /// This method must not be called concurrently with any DMA allocation or mapping primitives,
102    /// such as [`Coherent::zeroed`].
103    unsafe fn dma_set_mask_and_coherent(&self, mask: DmaMask) -> Result {
104        // SAFETY:
105        // - By the type invariant of `device::Device`, `self.as_ref().as_raw()` is valid.
106        // - The safety requirement of this function guarantees that there are no concurrent calls
107        //   to DMA allocation and mapping primitives using this mask.
108        to_result(unsafe {
109            bindings::dma_set_mask_and_coherent(self.as_ref().as_raw(), mask.value())
110        })
111    }
112
113    /// Set the maximum size of a single DMA segment the device may request.
114    ///
115    /// This method is usually called once from `probe()` as soon as the device capabilities are
116    /// known.
117    ///
118    /// # Safety
119    ///
120    /// This method must not be called concurrently with any DMA allocation or mapping primitives,
121    /// such as [`Coherent::zeroed`].
122    unsafe fn dma_set_max_seg_size(&self, size: u32) {
123        // SAFETY:
124        // - By the type invariant of `device::Device`, `self.as_ref().as_raw()` is valid.
125        // - The safety requirement of this function guarantees that there are no concurrent calls
126        //   to DMA allocation and mapping primitives using this parameter.
127        unsafe { bindings::dma_set_max_seg_size(self.as_ref().as_raw(), size) }
128    }
129}
130
131/// A DMA mask that holds a bitmask with the lowest `n` bits set.
132///
133/// Use [`DmaMask::new`] or [`DmaMask::try_new`] to construct a value. Values
134/// are guaranteed to never exceed the bit width of `u64`.
135///
136/// This is the Rust equivalent of the C macro `DMA_BIT_MASK()`.
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub struct DmaMask(u64);
139
140impl DmaMask {
141    /// Constructs a `DmaMask` with the lowest `n` bits set to `1`.
142    ///
143    /// For `n <= 64`, sets exactly the lowest `n` bits.
144    /// For `n > 64`, results in a build error.
145    ///
146    /// # Examples
147    ///
148    /// ```
149    /// use kernel::dma::DmaMask;
150    ///
151    /// let mask0 = DmaMask::new::<0>();
152    /// assert_eq!(mask0.value(), 0);
153    ///
154    /// let mask1 = DmaMask::new::<1>();
155    /// assert_eq!(mask1.value(), 0b1);
156    ///
157    /// let mask64 = DmaMask::new::<64>();
158    /// assert_eq!(mask64.value(), u64::MAX);
159    ///
160    /// // Build failure.
161    /// // let mask_overflow = DmaMask::new::<100>();
162    /// ```
163    #[inline]
164    pub const fn new<const N: u32>() -> Self {
165        let Ok(mask) = Self::try_new(N) else {
166            build_error!("Invalid DMA Mask.");
167        };
168
169        mask
170    }
171
172    /// Constructs a `DmaMask` with the lowest `n` bits set to `1`.
173    ///
174    /// For `n <= 64`, sets exactly the lowest `n` bits.
175    /// For `n > 64`, returns [`EINVAL`].
176    ///
177    /// # Examples
178    ///
179    /// ```
180    /// use kernel::dma::DmaMask;
181    ///
182    /// let mask0 = DmaMask::try_new(0)?;
183    /// assert_eq!(mask0.value(), 0);
184    ///
185    /// let mask1 = DmaMask::try_new(1)?;
186    /// assert_eq!(mask1.value(), 0b1);
187    ///
188    /// let mask64 = DmaMask::try_new(64)?;
189    /// assert_eq!(mask64.value(), u64::MAX);
190    ///
191    /// let mask_overflow = DmaMask::try_new(100);
192    /// assert!(mask_overflow.is_err());
193    /// # Ok::<(), Error>(())
194    /// ```
195    #[inline]
196    pub const fn try_new(n: u32) -> Result<Self> {
197        Ok(Self(match n {
198            0 => 0,
199            1..=64 => u64::MAX >> (64 - n),
200            _ => return Err(EINVAL),
201        }))
202    }
203
204    /// Returns the underlying `u64` bitmask value.
205    #[inline]
206    pub const fn value(&self) -> u64 {
207        self.0
208    }
209}
210
211/// Possible attributes associated with a DMA mapping.
212///
213/// They can be combined with the operators `|`, `&`, and `!`.
214///
215/// Values can be used from the [`attrs`] module.
216///
217/// # Examples
218///
219/// ```
220/// # use kernel::device::{Bound, Device};
221/// use kernel::dma::{attrs::*, Coherent};
222///
223/// # fn test(dev: &Device<Bound>) -> Result {
224/// let attribs = DMA_ATTR_FORCE_CONTIGUOUS | DMA_ATTR_NO_WARN;
225/// let c: Coherent<'_, [u64]> =
226///     Coherent::zeroed_slice_with_attrs(dev, 4, GFP_KERNEL, attribs)?;
227/// # Ok::<(), Error>(()) }
228/// ```
229#[derive(Clone, Copy, PartialEq)]
230#[repr(transparent)]
231pub struct Attrs(u32);
232
233impl Attrs {
234    /// Get the raw representation of this attribute.
235    pub(crate) fn as_raw(self) -> crate::ffi::c_ulong {
236        self.0 as crate::ffi::c_ulong
237    }
238
239    /// Check whether `flags` is contained in `self`.
240    pub fn contains(self, flags: Attrs) -> bool {
241        (self & flags) == flags
242    }
243}
244
245impl core::ops::BitOr for Attrs {
246    type Output = Self;
247    fn bitor(self, rhs: Self) -> Self::Output {
248        Self(self.0 | rhs.0)
249    }
250}
251
252impl core::ops::BitAnd for Attrs {
253    type Output = Self;
254    fn bitand(self, rhs: Self) -> Self::Output {
255        Self(self.0 & rhs.0)
256    }
257}
258
259impl core::ops::Not for Attrs {
260    type Output = Self;
261    fn not(self) -> Self::Output {
262        Self(!self.0)
263    }
264}
265
266/// DMA mapping attributes.
267pub mod attrs {
268    use super::Attrs;
269
270    /// Specifies that reads and writes to the mapping may be weakly ordered, that is that reads
271    /// and writes may pass each other.
272    pub const DMA_ATTR_WEAK_ORDERING: Attrs = Attrs(bindings::DMA_ATTR_WEAK_ORDERING);
273
274    /// Specifies that writes to the mapping may be buffered to improve performance.
275    pub const DMA_ATTR_WRITE_COMBINE: Attrs = Attrs(bindings::DMA_ATTR_WRITE_COMBINE);
276
277    /// Allows platform code to skip synchronization of the CPU cache for the given buffer assuming
278    /// that it has been already transferred to 'device' domain.
279    pub const DMA_ATTR_SKIP_CPU_SYNC: Attrs = Attrs(bindings::DMA_ATTR_SKIP_CPU_SYNC);
280
281    /// Forces contiguous allocation of the buffer in physical memory.
282    pub const DMA_ATTR_FORCE_CONTIGUOUS: Attrs = Attrs(bindings::DMA_ATTR_FORCE_CONTIGUOUS);
283
284    /// Hints DMA-mapping subsystem that it's probably not worth the time to try
285    /// to allocate memory to in a way that gives better TLB efficiency.
286    pub const DMA_ATTR_ALLOC_SINGLE_PAGES: Attrs = Attrs(bindings::DMA_ATTR_ALLOC_SINGLE_PAGES);
287
288    /// This tells the DMA-mapping subsystem to suppress allocation failure reports (similarly to
289    /// `__GFP_NOWARN`).
290    pub const DMA_ATTR_NO_WARN: Attrs = Attrs(bindings::DMA_ATTR_NO_WARN);
291
292    /// Indicates that the buffer is fully accessible at an elevated privilege level (and
293    /// ideally inaccessible or at least read-only at lesser-privileged levels).
294    pub const DMA_ATTR_PRIVILEGED: Attrs = Attrs(bindings::DMA_ATTR_PRIVILEGED);
295
296    /// Indicates that the buffer is MMIO memory.
297    pub const DMA_ATTR_MMIO: Attrs = Attrs(bindings::DMA_ATTR_MMIO);
298}
299
300/// DMA data direction.
301///
302/// Corresponds to the C [`enum dma_data_direction`].
303///
304/// [`enum dma_data_direction`]: srctree/include/linux/dma-direction.h
305#[derive(Copy, Clone, PartialEq, Eq, Debug)]
306#[repr(u32)]
307pub enum DataDirection {
308    /// The DMA mapping is for bidirectional data transfer.
309    ///
310    /// This is used when the buffer can be both read from and written to by the device.
311    /// The cache for the corresponding memory region is both flushed and invalidated.
312    Bidirectional = Self::const_cast(bindings::dma_data_direction::DMA_BIDIRECTIONAL),
313
314    /// The DMA mapping is for data transfer from memory to the device (write).
315    ///
316    /// The CPU has prepared data in the buffer, and the device will read it.
317    /// The cache for the corresponding memory region is flushed before device access.
318    ToDevice = Self::const_cast(bindings::dma_data_direction::DMA_TO_DEVICE),
319
320    /// The DMA mapping is for data transfer from the device to memory (read).
321    ///
322    /// The device will write data into the buffer for the CPU to read.
323    /// The cache for the corresponding memory region is invalidated before CPU access.
324    FromDevice = Self::const_cast(bindings::dma_data_direction::DMA_FROM_DEVICE),
325
326    /// The DMA mapping is not for data transfer.
327    ///
328    /// This is primarily for debugging purposes. With this direction, the DMA mapping API
329    /// will not perform any cache coherency operations.
330    None = Self::const_cast(bindings::dma_data_direction::DMA_NONE),
331}
332
333impl DataDirection {
334    /// Casts the bindgen-generated enum type to a `u32` at compile time.
335    ///
336    /// This function will cause a compile-time error if the underlying value of the
337    /// C enum is out of bounds for `u32`.
338    const fn const_cast(val: bindings::dma_data_direction) -> u32 {
339        // CAST: The C standard allows compilers to choose different integer types for enums.
340        // To safely check the value, we cast it to a wide signed integer type (`i128`)
341        // which can hold any standard C integer enum type without truncation.
342        let wide_val = val.0 as i128;
343
344        // Check if the value is outside the valid range for the target type `u32`.
345        // CAST: `u32::MAX` is cast to `i128` to match the type of `wide_val` for the comparison.
346        if wide_val < 0 || wide_val > u32::MAX as i128 {
347            // Trigger a compile-time error in a const context.
348            build_error!("C enum value is out of bounds for the target type `u32`.");
349        }
350
351        // CAST: This cast is valid because the check above guarantees that `wide_val`
352        // is within the representable range of `u32`.
353        wide_val as u32
354    }
355}
356
357impl From<DataDirection> for bindings::dma_data_direction {
358    /// Returns the raw representation of [`enum dma_data_direction`].
359    fn from(direction: DataDirection) -> Self {
360        match direction {
361            DataDirection::Bidirectional => Self::DMA_BIDIRECTIONAL,
362            DataDirection::ToDevice => Self::DMA_TO_DEVICE,
363            DataDirection::FromDevice => Self::DMA_FROM_DEVICE,
364            DataDirection::None => Self::DMA_NONE,
365        }
366    }
367}
368
369/// CPU-owned DMA allocation that can be converted into a device-shared [`Coherent`] object.
370///
371/// Unlike [`Coherent`], a [`CoherentBox`] is guaranteed to be fully owned by the CPU -- its DMA
372/// address is not exposed and it cannot be accessed by a device. This means it can safely be used
373/// like a normal boxed allocation (e.g. direct reads, writes, and mutable slices are all safe).
374///
375/// A typical use is to allocate a [`CoherentBox`], populate it with normal CPU access, and then
376/// convert it into a [`Coherent`] object to share it with the device.
377///
378/// # Examples
379///
380/// `CoherentBox<T>`:
381///
382/// ```
383/// # use kernel::device::{
384/// #     Bound,
385/// #     Device,
386/// # };
387/// use kernel::dma::{attrs::*,
388///     Coherent,
389///     CoherentBox,
390/// };
391///
392/// # fn test(dev: &Device<Bound>) -> Result {
393/// let mut dmem: CoherentBox<'_, u64> = CoherentBox::zeroed(dev, GFP_KERNEL)?;
394/// *dmem = 42;
395/// let dmem: Coherent<'_, u64> = dmem.into();
396/// # Ok::<(), Error>(()) }
397/// ```
398///
399/// `CoherentBox<[T]>`:
400///
401///
402/// ```
403/// # use kernel::device::{
404/// #     Bound,
405/// #     Device,
406/// # };
407/// use kernel::dma::{attrs::*,
408///     Coherent,
409///     CoherentBox,
410/// };
411///
412/// # fn test(dev: &Device<Bound>) -> Result {
413/// let mut dmem: CoherentBox<'_, [u64]> = CoherentBox::zeroed_slice(dev, 4, GFP_KERNEL)?;
414/// dmem.fill(42);
415/// let dmem: Coherent<'_, [u64]> = dmem.into();
416/// # Ok::<(), Error>(()) }
417/// ```
418pub struct CoherentBox<'a, T: KnownSize + ?Sized>(Coherent<'a, T>);
419
420impl<'a, T: AsBytes + FromBytes> CoherentBox<'a, [T]> {
421    /// [`CoherentBox`] variant of [`Coherent::zeroed_slice_with_attrs`].
422    #[inline]
423    pub fn zeroed_slice_with_attrs(
424        dev: &'a device::Device<Bound>,
425        count: usize,
426        gfp_flags: kernel::alloc::Flags,
427        dma_attrs: Attrs,
428    ) -> Result<Self> {
429        Coherent::zeroed_slice_with_attrs(dev, count, gfp_flags, dma_attrs).map(Self)
430    }
431
432    /// Same as [CoherentBox::zeroed_slice_with_attrs], but with `dma::Attrs(0)`.
433    #[inline]
434    pub fn zeroed_slice(
435        dev: &'a device::Device<Bound>,
436        count: usize,
437        gfp_flags: kernel::alloc::Flags,
438    ) -> Result<Self> {
439        Self::zeroed_slice_with_attrs(dev, count, gfp_flags, Attrs(0))
440    }
441
442    /// Initializes the element at `i` using the given initializer.
443    ///
444    /// Returns `EINVAL` if `i` is out of bounds.
445    pub fn init_at<E>(&mut self, i: usize, init: impl Init<T, E>) -> Result
446    where
447        Error: From<E>,
448    {
449        if i >= self.0.len() {
450            return Err(EINVAL);
451        }
452
453        let ptr = &raw mut self[i];
454
455        // SAFETY:
456        // - `ptr` is valid, properly aligned, and within this allocation.
457        // - `T: AsBytes + FromBytes` guarantees all bit patterns are valid, so partial writes on
458        //   error cannot leave the element in an invalid state.
459        // - The DMA address has not been exposed yet, so there is no concurrent device access.
460        unsafe { pin_init::raw_try_init(ptr, init)? };
461
462        Ok(())
463    }
464
465    /// Allocates a region of coherent memory of the same size as `data` and initializes it with a
466    /// copy of its contents.
467    ///
468    /// This is the [`CoherentBox`] variant of [`Coherent::from_slice_with_attrs`].
469    ///
470    /// # Examples
471    ///
472    /// ```
473    /// use core::ops::Deref;
474    ///
475    /// # use kernel::device::{Bound, Device};
476    /// use kernel::dma::{
477    ///     attrs::*,
478    ///     CoherentBox
479    /// };
480    ///
481    /// # fn test(dev: &Device<Bound>) -> Result {
482    /// let data = [0u8, 1u8, 2u8, 3u8];
483    /// let c: CoherentBox<'_, [u8]> =
484    ///     CoherentBox::from_slice_with_attrs(dev, &data, GFP_KERNEL, DMA_ATTR_NO_WARN)?;
485    ///
486    /// assert_eq!(c.deref(), &data);
487    /// # Ok::<(), Error>(()) }
488    /// ```
489    pub fn from_slice_with_attrs(
490        dev: &'a device::Device<Bound>,
491        data: &[T],
492        gfp_flags: kernel::alloc::Flags,
493        dma_attrs: Attrs,
494    ) -> Result<Self>
495    where
496        T: Copy,
497    {
498        let mut slice = Self(Coherent::<T>::alloc_slice_with_attrs(
499            dev,
500            data.len(),
501            gfp_flags,
502            dma_attrs,
503        )?);
504
505        // PANIC: `slice` was created with length `data.len()`.
506        slice.copy_from_slice(data);
507
508        Ok(slice)
509    }
510
511    /// Performs the same functionality as [`CoherentBox::from_slice_with_attrs`], except the
512    /// `dma_attrs` is 0 by default.
513    #[inline]
514    pub fn from_slice(
515        dev: &'a device::Device<Bound>,
516        data: &[T],
517        gfp_flags: kernel::alloc::Flags,
518    ) -> Result<Self>
519    where
520        T: Copy,
521    {
522        Self::from_slice_with_attrs(dev, data, gfp_flags, Attrs(0))
523    }
524}
525
526impl<'a, T: AsBytes + FromBytes> CoherentBox<'a, T> {
527    /// Same as [`CoherentBox::zeroed_slice_with_attrs`], but for a single element.
528    #[inline]
529    pub fn zeroed_with_attrs(
530        dev: &'a device::Device<Bound>,
531        gfp_flags: kernel::alloc::Flags,
532        dma_attrs: Attrs,
533    ) -> Result<Self> {
534        Coherent::zeroed_with_attrs(dev, gfp_flags, dma_attrs).map(Self)
535    }
536
537    /// Same as [`CoherentBox::zeroed_slice`], but for a single element.
538    #[inline]
539    pub fn zeroed(dev: &'a device::Device<Bound>, gfp_flags: kernel::alloc::Flags) -> Result<Self> {
540        Self::zeroed_with_attrs(dev, gfp_flags, Attrs(0))
541    }
542}
543
544impl<T: KnownSize + ?Sized> Deref for CoherentBox<'_, T> {
545    type Target = T;
546
547    #[inline]
548    fn deref(&self) -> &Self::Target {
549        // SAFETY:
550        // - We have not exposed the DMA address yet, so there can't be any concurrent access by a
551        //   device.
552        // - We have exclusive access to `self.0`.
553        unsafe { self.0.as_ref() }
554    }
555}
556
557impl<T: AsBytes + FromBytes + KnownSize + ?Sized> DerefMut for CoherentBox<'_, T> {
558    #[inline]
559    fn deref_mut(&mut self) -> &mut Self::Target {
560        // SAFETY:
561        // - We have not exposed the DMA address yet, so there can't be any concurrent access by a
562        //   device.
563        // - We have exclusive access to `self.0`.
564        unsafe { self.0.as_mut() }
565    }
566}
567
568impl<'a, T: AsBytes + FromBytes + KnownSize + ?Sized> From<CoherentBox<'a, T>> for Coherent<'a, T> {
569    #[inline]
570    fn from(value: CoherentBox<'a, T>) -> Self {
571        value.0
572    }
573}
574
575/// An abstraction of the `dma_alloc_coherent` API.
576///
577/// This is an abstraction around the `dma_alloc_coherent` API which is used to allocate and map
578/// large coherent DMA regions.
579///
580/// A [`Coherent`] instance contains a pointer to the allocated region (in the
581/// processor's virtual address space) and the device address which can be given to the device
582/// as the DMA address base of the region. The region is released once [`Coherent`]
583/// is dropped.
584///
585/// # Invariants
586///
587/// - For the lifetime of an instance of [`Coherent`], the `cpu_addr` is a valid pointer
588///   to an allocated region of coherent memory and `dma_addr` is the DMA address base of the
589///   region.
590/// - The size in bytes of the allocation is equal to size information via pointer.
591//
592// The lifetime parameter ties DMA allocations to the device's bound scope, ensuring they are freed
593// before the device is unbound under normal circumstances. However, if a `Coherent` is leaked (e.g.
594// via `mem::forget`), device resources such as IOMMU mappings will not be released.  Making all
595// constructors `unsafe` to prevent this is considered too restrictive for the common case; this
596// soundness hole is accepted for now.
597pub struct Coherent<'a, T: KnownSize + ?Sized> {
598    dev: &'a device::Device<Bound>,
599    dma_addr: DmaAddress,
600    cpu_addr: NonNull<T>,
601    dma_attrs: Attrs,
602}
603
604impl<T: KnownSize + ?Sized> Coherent<'_, T> {
605    /// Returns the size in bytes of this allocation.
606    #[inline]
607    pub fn size(&self) -> usize {
608        T::size(self.cpu_addr.as_ptr())
609    }
610
611    /// Returns the raw pointer to the allocated region in the CPU's virtual address space.
612    #[inline]
613    pub fn as_ptr(&self) -> *const T {
614        self.cpu_addr.as_ptr()
615    }
616
617    /// Returns the raw pointer to the allocated region in the CPU's virtual address space as
618    /// a mutable pointer.
619    #[inline]
620    pub fn as_mut_ptr(&self) -> *mut T {
621        self.cpu_addr.as_ptr()
622    }
623
624    /// Returns a DMA address which may be given to the device as the base of the region.
625    #[inline]
626    pub fn dma_address(&self) -> DmaAddress {
627        self.dma_addr
628    }
629
630    /// Returns a reference to the data in the region.
631    ///
632    /// # Safety
633    ///
634    /// * Callers must ensure that the device does not read/write to/from memory while the returned
635    ///   slice is live.
636    /// * Callers must ensure that this call does not race with a write to the same region while
637    ///   the returned slice is live.
638    #[inline]
639    pub unsafe fn as_ref(&self) -> &T {
640        // SAFETY: per safety requirement.
641        unsafe { &*self.as_ptr() }
642    }
643
644    /// Returns a mutable reference to the data in the region.
645    ///
646    /// # Safety
647    ///
648    /// * Callers must ensure that the device does not read/write to/from memory while the returned
649    ///   slice is live.
650    /// * Callers must ensure that this call does not race with a read or write to the same region
651    ///   while the returned slice is live.
652    #[expect(clippy::mut_from_ref, reason = "unsafe to use API")]
653    #[inline]
654    pub unsafe fn as_mut(&self) -> &mut T {
655        // SAFETY: per safety requirement.
656        unsafe { &mut *self.as_mut_ptr() }
657    }
658}
659
660impl<'a, T: AsBytes + FromBytes> Coherent<'a, T> {
661    /// Allocates a region of `T` of coherent memory.
662    fn alloc_with_attrs(
663        dev: &'a device::Device<Bound>,
664        gfp_flags: kernel::alloc::Flags,
665        dma_attrs: Attrs,
666    ) -> Result<Self> {
667        const {
668            assert!(
669                core::mem::size_of::<T>() > 0,
670                "It doesn't make sense for the allocated type to be a ZST"
671            );
672        }
673
674        let mut dma_addr = 0;
675        // SAFETY: Device pointer is guaranteed as valid by the type invariant on `Device`.
676        let addr = unsafe {
677            bindings::dma_alloc_attrs(
678                dev.as_raw(),
679                core::mem::size_of::<T>(),
680                &mut dma_addr,
681                gfp_flags.as_raw(),
682                dma_attrs.as_raw(),
683            )
684        };
685        let cpu_addr = NonNull::new(addr.cast()).ok_or(ENOMEM)?;
686        // INVARIANT:
687        // - We just successfully allocated a coherent region which is adequately sized for `T`,
688        //   hence the cpu address is valid.
689        // - `dev` is a valid reference to a bound device that outlives this allocation.
690        Ok(Self {
691            dev,
692            dma_addr,
693            cpu_addr,
694            dma_attrs,
695        })
696    }
697
698    /// Allocates a region of type `T` of coherent memory.
699    ///
700    /// # Examples
701    ///
702    /// ```
703    /// # use kernel::device::{
704    /// #     Bound,
705    /// #     Device,
706    /// # };
707    /// use kernel::dma::{
708    ///     attrs::*,
709    ///     Coherent,
710    /// };
711    ///
712    /// # fn test(dev: &Device<Bound>) -> Result {
713    /// let c: Coherent<'_, [u64; 4]> =
714    ///     Coherent::zeroed_with_attrs(dev, GFP_KERNEL, DMA_ATTR_NO_WARN)?;
715    /// # Ok::<(), Error>(()) }
716    /// ```
717    #[inline]
718    pub fn zeroed_with_attrs(
719        dev: &'a device::Device<Bound>,
720        gfp_flags: kernel::alloc::Flags,
721        dma_attrs: Attrs,
722    ) -> Result<Self> {
723        Self::alloc_with_attrs(dev, gfp_flags | __GFP_ZERO, dma_attrs)
724    }
725
726    /// Performs the same functionality as [`Coherent::zeroed_with_attrs`], except the
727    /// `dma_attrs` is 0 by default.
728    #[inline]
729    pub fn zeroed(dev: &'a device::Device<Bound>, gfp_flags: kernel::alloc::Flags) -> Result<Self> {
730        Self::zeroed_with_attrs(dev, gfp_flags, Attrs(0))
731    }
732
733    /// Same as [`Coherent::zeroed_with_attrs`], but instead of a zero-initialization the memory is
734    /// initialized with `init`.
735    pub fn init_with_attrs<E>(
736        dev: &'a device::Device<Bound>,
737        gfp_flags: kernel::alloc::Flags,
738        dma_attrs: Attrs,
739        init: impl Init<T, E>,
740    ) -> Result<Self>
741    where
742        Error: From<E>,
743    {
744        let dmem = Self::alloc_with_attrs(dev, gfp_flags, dma_attrs)?;
745        let ptr = dmem.as_mut_ptr();
746
747        // SAFETY:
748        // - `ptr` is valid, properly aligned, and points to exclusively owned memory.
749        // - If `raw_try_init` fails, `self` is dropped, which safely frees the underlying
750        //   `Coherent`'s DMA memory. `T: AsBytes + FromBytes` ensures there are no complex `Drop`
751        //   requirements we are bypassing.
752        unsafe { pin_init::raw_try_init(ptr, init)? };
753
754        Ok(dmem)
755    }
756
757    /// Same as [`Coherent::zeroed`], but instead of a zero-initialization the memory is initialized
758    /// with `init`.
759    #[inline]
760    pub fn init<E>(
761        dev: &'a device::Device<Bound>,
762        gfp_flags: kernel::alloc::Flags,
763        init: impl Init<T, E>,
764    ) -> Result<Self>
765    where
766        Error: From<E>,
767    {
768        Self::init_with_attrs(dev, gfp_flags, Attrs(0), init)
769    }
770
771    /// Allocates a region of `[T; len]` of coherent memory.
772    fn alloc_slice_with_attrs(
773        dev: &'a device::Device<Bound>,
774        len: usize,
775        gfp_flags: kernel::alloc::Flags,
776        dma_attrs: Attrs,
777    ) -> Result<Coherent<'a, [T]>> {
778        const {
779            assert!(
780                core::mem::size_of::<T>() > 0,
781                "It doesn't make sense for the allocated type to be a ZST"
782            );
783        }
784
785        // `dma_alloc_attrs` cannot handle zero-length allocation, bail early.
786        if len == 0 {
787            Err(EINVAL)?;
788        }
789
790        let size = core::mem::size_of::<T>().checked_mul(len).ok_or(ENOMEM)?;
791        let mut dma_addr = 0;
792        // SAFETY: Device pointer is guaranteed as valid by the type invariant on `Device`.
793        let addr = unsafe {
794            bindings::dma_alloc_attrs(
795                dev.as_raw(),
796                size,
797                &mut dma_addr,
798                gfp_flags.as_raw(),
799                dma_attrs.as_raw(),
800            )
801        };
802        let cpu_addr = NonNull::slice_from_raw_parts(NonNull::new(addr.cast()).ok_or(ENOMEM)?, len);
803        // INVARIANT:
804        // - We just successfully allocated a coherent region which is adequately sized for
805        //   `[T; len]`, hence the cpu address is valid.
806        // - `dev` is a valid reference to a bound device that outlives this allocation.
807        Ok(Coherent {
808            dev,
809            dma_addr,
810            cpu_addr,
811            dma_attrs,
812        })
813    }
814
815    /// Allocates a zeroed region of type `T` of coherent memory.
816    ///
817    /// Unlike `Coherent::<[T; N]>::zeroed_with_attrs`, `Coherent::<T>::zeroed_slices` support
818    /// a runtime length.
819    ///
820    /// # Examples
821    ///
822    /// ```
823    /// # use kernel::device::{
824    /// #     Bound,
825    /// #     Device,
826    /// # };
827    /// use kernel::dma::{
828    ///     attrs::*,
829    ///     Coherent,
830    /// };
831    ///
832    /// # fn test(dev: &Device<Bound>) -> Result {
833    /// let c: Coherent<'_, [u64]> =
834    ///     Coherent::zeroed_slice_with_attrs(dev, 4, GFP_KERNEL, DMA_ATTR_NO_WARN)?;
835    /// # Ok::<(), Error>(()) }
836    /// ```
837    #[inline]
838    pub fn zeroed_slice_with_attrs(
839        dev: &'a device::Device<Bound>,
840        len: usize,
841        gfp_flags: kernel::alloc::Flags,
842        dma_attrs: Attrs,
843    ) -> Result<Coherent<'a, [T]>> {
844        Coherent::alloc_slice_with_attrs(dev, len, gfp_flags | __GFP_ZERO, dma_attrs)
845    }
846
847    /// Performs the same functionality as [`Coherent::zeroed_slice_with_attrs`], except the
848    /// `dma_attrs` is 0 by default.
849    #[inline]
850    pub fn zeroed_slice(
851        dev: &'a device::Device<Bound>,
852        len: usize,
853        gfp_flags: kernel::alloc::Flags,
854    ) -> Result<Coherent<'a, [T]>> {
855        Self::zeroed_slice_with_attrs(dev, len, gfp_flags, Attrs(0))
856    }
857
858    /// Allocates a region of coherent memory of the same size as `data` and initializes it with a
859    /// copy of its contents.
860    ///
861    /// # Examples
862    ///
863    /// ```
864    /// # use kernel::device::{Bound, Device};
865    /// use kernel::dma::{
866    ///     attrs::*,
867    ///     Coherent
868    /// };
869    ///
870    /// # fn test(dev: &Device<Bound>) -> Result {
871    /// let data = [0u8, 1u8, 2u8, 3u8];
872    /// // `c` has the same content as `data`.
873    /// let c: Coherent<'_, [u8]> =
874    ///     Coherent::from_slice_with_attrs(dev, &data, GFP_KERNEL, DMA_ATTR_NO_WARN)?;
875    ///
876    /// # Ok::<(), Error>(()) }
877    /// ```
878    #[inline]
879    pub fn from_slice_with_attrs(
880        dev: &'a device::Device<Bound>,
881        data: &[T],
882        gfp_flags: kernel::alloc::Flags,
883        dma_attrs: Attrs,
884    ) -> Result<Coherent<'a, [T]>>
885    where
886        T: Copy,
887    {
888        CoherentBox::from_slice_with_attrs(dev, data, gfp_flags, dma_attrs).map(Into::into)
889    }
890
891    /// Performs the same functionality as [`Coherent::from_slice_with_attrs`], except the
892    /// `dma_attrs` is 0 by default.
893    #[inline]
894    pub fn from_slice(
895        dev: &'a device::Device<Bound>,
896        data: &[T],
897        gfp_flags: kernel::alloc::Flags,
898    ) -> Result<Coherent<'a, [T]>>
899    where
900        T: Copy,
901    {
902        Self::from_slice_with_attrs(dev, data, gfp_flags, Attrs(0))
903    }
904}
905
906impl<T> Coherent<'_, [T]> {
907    /// Returns the number of elements `T` in this allocation.
908    ///
909    /// Note that this is not the size of the allocation in bytes, which is provided by
910    /// [`Self::size`].
911    #[inline]
912    #[expect(clippy::len_without_is_empty, reason = "Coherent slice is never empty")]
913    pub fn len(&self) -> usize {
914        self.cpu_addr.len()
915    }
916}
917
918/// Note that the device configured to do DMA must be halted before this object is dropped.
919impl<T: KnownSize + ?Sized> Drop for Coherent<'_, T> {
920    fn drop(&mut self) {
921        let size = T::size(self.cpu_addr.as_ptr());
922        // SAFETY: Device pointer is guaranteed as valid by the lifetime of this `Coherent`.
923        // The cpu address, and the dma address are valid due to the type invariants on
924        // `Coherent`.
925        unsafe {
926            bindings::dma_free_attrs(
927                self.dev.as_raw(),
928                size,
929                self.cpu_addr.as_ptr().cast(),
930                self.dma_addr,
931                self.dma_attrs.as_raw(),
932            )
933        }
934    }
935}
936
937// SAFETY: It is safe to send a `Coherent` to another thread if `T`
938// can be sent to another thread.
939unsafe impl<T: KnownSize + Send + ?Sized> Send for Coherent<'_, T> {}
940
941// SAFETY: Sharing `&Coherent` across threads is safe if `T` is `Sync`, because all
942// methods that access the buffer contents (`field_read`, `field_write`, `as_slice`,
943// `as_slice_mut`) are `unsafe`, and callers are responsible for ensuring no data races occur.
944// The safe methods only return metadata or raw pointers whose use requires `unsafe`.
945unsafe impl<T: KnownSize + ?Sized + AsBytes + FromBytes + Sync> Sync for Coherent<'_, T> {}
946
947impl<T: KnownSize + AsBytes + ?Sized> debugfs::BinaryWriter for Coherent<'_, T> {
948    fn write_to_slice(
949        &self,
950        writer: &mut UserSliceWriter,
951        offset: &mut file::Offset,
952    ) -> Result<usize> {
953        if offset.is_negative() {
954            return Err(EINVAL);
955        }
956
957        // If the offset is too large for a usize (e.g. on 32-bit platforms),
958        // then consider that as past EOF and just return 0 bytes.
959        let Ok(offset_val) = usize::try_from(*offset) else {
960            return Ok(0);
961        };
962
963        if offset_val >= self.size() {
964            return Ok(0);
965        }
966
967        let count = (self.size() - offset_val).min(writer.len());
968
969        writer.write_dma(self, offset_val, count)?;
970
971        *offset += count as i64;
972        Ok(count)
973    }
974}
975
976/// An opaque DMA allocation without a kernel virtual mapping.
977///
978/// Unlike [`Coherent`], a `CoherentHandle` does not provide CPU access to the allocated memory.
979/// The allocation is always performed with `DMA_ATTR_NO_KERNEL_MAPPING`, meaning no kernel
980/// virtual mapping is created for the buffer. The value returned by the C API as the CPU
981/// address is an opaque handle used only to free the allocation.
982///
983/// This is useful for buffers that are only ever accessed by hardware.
984///
985/// # Invariants
986///
987/// - `cpu_handle` holds the opaque handle returned by `dma_alloc_attrs` with
988///   `DMA_ATTR_NO_KERNEL_MAPPING` set, and is only valid for passing back to `dma_free_attrs`.
989/// - `dma_addr` is the corresponding bus address for device DMA.
990/// - `size` is the allocation size in bytes as passed to `dma_alloc_attrs`.
991/// - `dma_attrs` contains the attributes used for the allocation, always including
992///   `DMA_ATTR_NO_KERNEL_MAPPING`.
993pub struct CoherentHandle<'a> {
994    dev: &'a device::Device<Bound>,
995    dma_addr: DmaAddress,
996    cpu_handle: NonNull<c_void>,
997    size: usize,
998    dma_attrs: Attrs,
999}
1000
1001impl<'a> CoherentHandle<'a> {
1002    /// Allocates `size` bytes of coherent DMA memory without creating a kernel virtual mapping.
1003    ///
1004    /// Additional DMA attributes may be passed via `dma_attrs`; `DMA_ATTR_NO_KERNEL_MAPPING` is
1005    /// always set implicitly.
1006    ///
1007    /// Returns `EINVAL` if `size` is zero, `ENOMEM` if the allocation fails.
1008    pub fn alloc_with_attrs(
1009        dev: &'a device::Device<Bound>,
1010        size: usize,
1011        gfp_flags: kernel::alloc::Flags,
1012        dma_attrs: Attrs,
1013    ) -> Result<Self> {
1014        if size == 0 {
1015            return Err(EINVAL);
1016        }
1017
1018        let dma_attrs = dma_attrs | Attrs(bindings::DMA_ATTR_NO_KERNEL_MAPPING);
1019        let mut dma_addr = 0;
1020        // SAFETY: `dev.as_raw()` is valid by the type invariant on `device::Device`.
1021        let cpu_handle = unsafe {
1022            bindings::dma_alloc_attrs(
1023                dev.as_raw(),
1024                size,
1025                &mut dma_addr,
1026                gfp_flags.as_raw(),
1027                dma_attrs.as_raw(),
1028            )
1029        };
1030
1031        let cpu_handle = NonNull::new(cpu_handle).ok_or(ENOMEM)?;
1032
1033        // INVARIANT: `cpu_handle` is the opaque handle from a successful `dma_alloc_attrs` call
1034        // with `DMA_ATTR_NO_KERNEL_MAPPING`, `dma_addr` is the corresponding DMA address,
1035        // and `dev` is a valid reference to a bound device that outlives this allocation.
1036        Ok(Self {
1037            dev,
1038            dma_addr,
1039            cpu_handle,
1040            size,
1041            dma_attrs,
1042        })
1043    }
1044
1045    /// Allocates `size` bytes of coherent DMA memory without creating a kernel virtual mapping.
1046    #[inline]
1047    pub fn alloc(
1048        dev: &'a device::Device<Bound>,
1049        size: usize,
1050        gfp_flags: kernel::alloc::Flags,
1051    ) -> Result<Self> {
1052        Self::alloc_with_attrs(dev, size, gfp_flags, Attrs(0))
1053    }
1054
1055    /// Returns the DMA address for this allocation.
1056    ///
1057    /// This address can be programmed into device hardware for DMA access.
1058    #[inline]
1059    pub fn dma_address(&self) -> DmaAddress {
1060        self.dma_addr
1061    }
1062
1063    /// Returns the size in bytes of this allocation.
1064    #[inline]
1065    pub fn size(&self) -> usize {
1066        self.size
1067    }
1068}
1069
1070impl Drop for CoherentHandle<'_> {
1071    fn drop(&mut self) {
1072        // SAFETY: All values are valid by the type invariants on `CoherentHandle`.
1073        // `cpu_handle` is the opaque handle from `dma_alloc_attrs` and is passed back unchanged.
1074        unsafe {
1075            bindings::dma_free_attrs(
1076                self.dev.as_raw(),
1077                self.size,
1078                self.cpu_handle.as_ptr(),
1079                self.dma_addr,
1080                self.dma_attrs.as_raw(),
1081            )
1082        }
1083    }
1084}
1085
1086// SAFETY: `CoherentHandle` only holds a device reference, a DMA address, an opaque CPU handle,
1087// and a size. None of these are tied to a specific thread.
1088unsafe impl Send for CoherentHandle<'_> {}
1089
1090// SAFETY: `CoherentHandle` provides no CPU access to the underlying allocation. The only
1091// operations on `&CoherentHandle` are reading the DMA address and size, both of which are
1092// plain `Copy` values.
1093unsafe impl Sync for CoherentHandle<'_> {}
1094
1095/// View type for `Coherent`.
1096///
1097/// This is same as [`SysMem`] but with additional information that allows handing out a DMA
1098/// address.
1099pub struct CoherentView<'a, T: ?Sized> {
1100    cpu_addr: SysMem<'a, T>,
1101    dma_addr: DmaAddress,
1102}
1103
1104impl<T: ?Sized> Copy for CoherentView<'_, T> {}
1105impl<T: ?Sized> Clone for CoherentView<'_, T> {
1106    #[inline]
1107    fn clone(&self) -> Self {
1108        *self
1109    }
1110}
1111
1112impl<'a, T: ?Sized> CoherentView<'a, T> {
1113    /// Erase the DMA address information and obtain a [`SysMem`] view of the same memory region.
1114    #[inline]
1115    pub fn as_sys_mem(self) -> SysMem<'a, T> {
1116        self.cpu_addr
1117    }
1118
1119    /// Returns the DMA address which may be given to the device as base of the region.
1120    #[inline]
1121    pub fn dma_address(self) -> DmaAddress {
1122        self.dma_addr
1123    }
1124
1125    /// Returns a reference to the data in the region.
1126    ///
1127    /// # Safety
1128    ///
1129    /// * Callers must ensure that the device does not read/write to/from memory while the returned
1130    ///   reference is live.
1131    /// * Callers must ensure that this call does not race with a write (including call to `as_mut`)
1132    ///   to the same region while the returned reference is live.
1133    #[inline]
1134    pub unsafe fn as_ref(self) -> &'a T {
1135        // SAFETY: pointer is aligned and valid per type invariant. Aliasing rule is satisfied per
1136        // safety requirement.
1137        unsafe { &*self.cpu_addr.as_ptr() }
1138    }
1139
1140    /// Returns a mutable reference to the data in the region.
1141    ///
1142    /// # Safety
1143    ///
1144    /// * Callers must ensure that the device does not read/write to/from memory while the returned
1145    ///   reference is live.
1146    /// * Callers must ensure that this call does not race with a read (including call to `as_ref`)
1147    ///   or write (including call to `as_mut`) to the same region while the returned reference is
1148    ///   live.
1149    #[inline]
1150    pub unsafe fn as_mut(self) -> &'a mut T {
1151        // SAFETY: pointer is aligned and valid per type invariant. Aliasing rule is satisfied per
1152        // safety requirement.
1153        unsafe { &mut *self.cpu_addr.as_ptr() }
1154    }
1155}
1156
1157/// `IoBackend` implementation for `Coherent`.
1158pub struct CoherentIoBackend;
1159
1160impl IoBackend for CoherentIoBackend {
1161    type View<'a, T: ?Sized + KnownSize> = CoherentView<'a, T>;
1162
1163    #[inline]
1164    fn as_ptr<'a, T: ?Sized + KnownSize>(view: Self::View<'a, T>) -> *mut T {
1165        SysMemBackend::as_ptr(view.cpu_addr)
1166    }
1167
1168    #[inline]
1169    unsafe fn project_view<'a, T: ?Sized + KnownSize, U: ?Sized + KnownSize>(
1170        view: Self::View<'a, T>,
1171        ptr: *mut U,
1172    ) -> Self::View<'a, U> {
1173        let offset = ptr.addr() - view.cpu_addr.as_ptr().addr();
1174        // CAST: The offset DMA address can never overflow.
1175        let dma_addr = view.dma_addr + offset as DmaAddress;
1176        CoherentView {
1177            dma_addr,
1178            // SAFETY: Per safety requirement.
1179            cpu_addr: unsafe { SysMemBackend::project_view(view.cpu_addr, ptr) },
1180        }
1181    }
1182}
1183
1184impl<T> IoCapable<T> for CoherentIoBackend
1185where
1186    SysMemBackend: IoCapable<T>,
1187{
1188    #[inline]
1189    fn io_read<'a>(view: Self::View<'a, T>) -> T {
1190        SysMemBackend::io_read(view.cpu_addr)
1191    }
1192
1193    #[inline]
1194    fn io_write<'a>(view: Self::View<'a, T>, value: T) {
1195        SysMemBackend::io_write(view.cpu_addr, value)
1196    }
1197}
1198
1199impl IoCopyable for CoherentIoBackend {
1200    #[inline]
1201    unsafe fn copy_from_io(view: Self::View<'_, [u8]>, buffer: *mut u8) {
1202        // SAFETY: Per safety requirement.
1203        unsafe { SysMemBackend::copy_from_io(view.cpu_addr, buffer) }
1204    }
1205
1206    #[inline]
1207    unsafe fn copy_to_io(view: Self::View<'_, [u8]>, buffer: *const u8) {
1208        // SAFETY: Per safety requirement.
1209        unsafe { SysMemBackend::copy_to_io(view.cpu_addr, buffer) }
1210    }
1211
1212    #[inline]
1213    fn copy_read<T: zerocopy::FromBytes>(view: Self::View<'_, T>) -> T {
1214        SysMemBackend::copy_read(view.cpu_addr)
1215    }
1216
1217    #[inline]
1218    fn copy_write<T: zerocopy::IntoBytes>(view: Self::View<'_, T>, value: T) {
1219        SysMemBackend::copy_write(view.cpu_addr, value)
1220    }
1221}
1222
1223impl<'a, T: ?Sized + KnownSize> IoBase<'a> for CoherentView<'a, T> {
1224    type Backend = CoherentIoBackend;
1225    type Target = T;
1226
1227    #[inline]
1228    fn as_view(self) -> CoherentView<'a, Self::Target> {
1229        self
1230    }
1231}
1232
1233impl<'a, T: ?Sized + KnownSize> IoBase<'a> for &'a Coherent<'_, T> {
1234    type Backend = CoherentIoBackend;
1235    type Target = T;
1236
1237    #[inline]
1238    fn as_view(self) -> CoherentView<'a, Self::Target> {
1239        CoherentView {
1240            // SAFETY: `cpu_addr` is valid and aligned kernel accessible memory.
1241            cpu_addr: unsafe { SysMem::new(self.cpu_addr.as_ptr()) },
1242            dma_addr: self.dma_addr,
1243        }
1244    }
1245}