xref: /linux/drivers/gpu/nova-core/dma.rs (revision 173c99b85aa05387fcfb3231293124c5d611d167)
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()).map(|mut dma_obj| {
34             // TODO[COHA]: replace with `CoherentAllocation::write()` once available.
35             // SAFETY:
36             // - `dma_obj`'s size is at least `data.len()`.
37             // - We have just created this object and there is no other user at this stage.
38             unsafe {
39                 core::ptr::copy_nonoverlapping(
40                     data.as_ptr(),
41                     dma_obj.dma.start_ptr_mut(),
42                     data.len(),
43                 );
44             }
45 
46             dma_obj
47         })
48     }
49 }
50 
51 impl Deref for DmaObject {
52     type Target = CoherentAllocation<u8>;
53 
54     fn deref(&self) -> &Self::Target {
55         &self.dma
56     }
57 }
58 
59 impl DerefMut for DmaObject {
60     fn deref_mut(&mut self) -> &mut Self::Target {
61         &mut self.dma
62     }
63 }
64