xref: /linux/drivers/gpu/nova-core/dma.rs (revision e54ad0cd3673c93cdafda58505eaa81610fe3aef)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! Simple DMA object wrapper.
4 
5 use core::ops::{
6     Deref,
7     DerefMut, //
8 };
9 
10 use kernel::{
11     device,
12     dma::CoherentAllocation,
13     page::PAGE_SIZE,
14     prelude::*, //
15 };
16 
17 pub(crate) struct DmaObject {
18     dma: CoherentAllocation<u8>,
19 }
20 
21 impl DmaObject {
22     pub(crate) fn new(dev: &device::Device<device::Bound>, len: usize) -> Result<Self> {
23         let len = core::alloc::Layout::from_size_align(len, PAGE_SIZE)
24             .map_err(|_| EINVAL)?
25             .pad_to_align()
26             .size();
27         let dma = CoherentAllocation::alloc_coherent(dev, len, GFP_KERNEL | __GFP_ZERO)?;
28 
29         Ok(Self { dma })
30     }
31 
32     pub(crate) fn from_data(dev: &device::Device<device::Bound>, data: &[u8]) -> Result<Self> {
33         Self::new(dev, data.len()).and_then(|mut dma_obj| {
34             // SAFETY: We have just allocated the DMA memory, we are the only users and
35             // we haven't made the device aware of the handle yet.
36             unsafe { dma_obj.write(data, 0)? }
37             Ok(dma_obj)
38         })
39     }
40 }
41 
42 impl Deref for DmaObject {
43     type Target = CoherentAllocation<u8>;
44 
45     fn deref(&self) -> &Self::Target {
46         &self.dma
47     }
48 }
49 
50 impl DerefMut for DmaObject {
51     fn deref_mut(&mut self) -> &mut Self::Target {
52         &mut self.dma
53     }
54 }
55