Linux kernel mirror (for testing)
git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel
os
linux
1// SPDX-License-Identifier: GPL-2.0
2
3//! Simple DMA object wrapper.
4
5use core::ops::{Deref, DerefMut};
6
7use kernel::device;
8use kernel::dma::CoherentAllocation;
9use kernel::page::PAGE_SIZE;
10use kernel::prelude::*;
11
12pub(crate) struct DmaObject {
13 dma: CoherentAllocation<u8>,
14}
15
16impl DmaObject {
17 pub(crate) fn new(dev: &device::Device<device::Bound>, len: usize) -> Result<Self> {
18 let len = core::alloc::Layout::from_size_align(len, PAGE_SIZE)
19 .map_err(|_| EINVAL)?
20 .pad_to_align()
21 .size();
22 let dma = CoherentAllocation::alloc_coherent(dev, len, GFP_KERNEL | __GFP_ZERO)?;
23
24 Ok(Self { dma })
25 }
26
27 pub(crate) fn from_data(dev: &device::Device<device::Bound>, data: &[u8]) -> Result<Self> {
28 Self::new(dev, data.len()).map(|mut dma_obj| {
29 // TODO[COHA]: replace with `CoherentAllocation::write()` once available.
30 // SAFETY:
31 // - `dma_obj`'s size is at least `data.len()`.
32 // - We have just created this object and there is no other user at this stage.
33 unsafe {
34 core::ptr::copy_nonoverlapping(
35 data.as_ptr(),
36 dma_obj.dma.start_ptr_mut(),
37 data.len(),
38 );
39 }
40
41 dma_obj
42 })
43 }
44}
45
46impl Deref for DmaObject {
47 type Target = CoherentAllocation<u8>;
48
49 fn deref(&self) -> &Self::Target {
50 &self.dma
51 }
52}
53
54impl DerefMut for DmaObject {
55 fn deref_mut(&mut self) -> &mut Self::Target {
56 &mut self.dma
57 }
58}