1 // SPDX-License-Identifier: GPL-2.0 2 3 //! Simple DMA object wrapper. 4 5 use core::ops::{Deref, DerefMut}; 6 7 use kernel::device; 8 use kernel::dma::CoherentAllocation; 9 use kernel::page::PAGE_SIZE; 10 use kernel::prelude::*; 11 12 pub(crate) struct DmaObject { 13 dma: CoherentAllocation<u8>, 14 } 15 16 impl DmaObject { new(dev: &device::Device<device::Bound>, len: usize) -> Result<Self>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 from_data(dev: &device::Device<device::Bound>, data: &[u8]) -> Result<Self>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 46 impl Deref for DmaObject { 47 type Target = CoherentAllocation<u8>; 48 deref(&self) -> &Self::Target49 fn deref(&self) -> &Self::Target { 50 &self.dma 51 } 52 } 53 54 impl DerefMut for DmaObject { deref_mut(&mut self) -> &mut Self::Target55 fn deref_mut(&mut self) -> &mut Self::Target { 56 &mut self.dma 57 } 58 } 59