Skip to main content

dma_api/
streaming.rs

1use alloc::vec::Vec;
2use core::{marker::PhantomData, num::NonZeroUsize, ops::Range, ptr::NonNull};
3
4use crate::{DeviceDma, DmaDirection, DmaError, DmaMapHandle, DmaPod};
5
6pub struct StreamingMap<T: DmaPod> {
7    handle: DmaMapHandle,
8    device: DeviceDma,
9    direction: DmaDirection,
10    _marker: PhantomData<*mut T>,
11}
12
13unsafe impl<T: DmaPod + Send> Send for StreamingMap<T> {}
14
15impl<T: DmaPod> StreamingMap<T> {
16    pub(crate) fn map(
17        os: &DeviceDma,
18        buff: &mut [T],
19        align: usize,
20        direction: DmaDirection,
21    ) -> Result<Self, DmaError> {
22        let addr = NonNull::new(buff.as_mut_ptr().cast::<u8>()).ok_or(DmaError::NullPointer)?;
23        let size =
24            NonZeroUsize::new(core::mem::size_of_val(buff)).ok_or(DmaError::ZeroSizedBuffer)?;
25        let handle = unsafe { os.map_streaming(addr, size, align, direction)? };
26
27        Ok(Self {
28            handle,
29            device: os.clone(),
30            direction,
31            _marker: PhantomData,
32        })
33    }
34
35    pub fn dma_addr(&self) -> crate::DmaAddr {
36        self.handle.dma_addr()
37    }
38
39    pub fn len(&self) -> usize {
40        if core::mem::size_of::<T>() == 0 {
41            0
42        } else {
43            self.handle.size() / core::mem::size_of::<T>()
44        }
45    }
46
47    pub fn is_empty(&self) -> bool {
48        self.len() == 0
49    }
50
51    pub fn bytes_len(&self) -> usize {
52        self.handle.size()
53    }
54
55    pub fn read_cpu(&self, index: usize) -> Option<T> {
56        if index >= self.len() {
57            return None;
58        }
59        Some(unsafe { self.handle.as_ptr().cast::<T>().add(index).read() })
60    }
61
62    pub fn set_cpu(&mut self, index: usize, value: T) {
63        assert!(
64            index < self.len(),
65            "index out of range, index: {}, len: {}",
66            index,
67            self.len()
68        );
69        unsafe {
70            self.handle.as_ptr().cast::<T>().add(index).write(value);
71        }
72    }
73
74    pub fn copy_from_slice_cpu(&mut self, src: &[T]) {
75        assert!(
76            core::mem::size_of_val(src) <= self.handle.size(),
77            "source slice is larger than DMA buffer"
78        );
79        unsafe {
80            self.handle
81                .as_ptr()
82                .cast::<T>()
83                .as_ptr()
84                .copy_from_nonoverlapping(src.as_ptr(), src.len());
85        }
86    }
87
88    pub fn write_with_cpu<R>(&mut self, len: usize, f: impl FnOnce(&mut [T]) -> R) -> R {
89        assert!(len <= self.len(), "range out of bounds");
90        let data = unsafe {
91            core::slice::from_raw_parts_mut(self.handle.as_ptr().cast::<T>().as_ptr(), len)
92        };
93        f(data)
94    }
95
96    pub fn read_with_cpu<R>(&self, len: usize, f: impl FnOnce(&[T]) -> R) -> R {
97        assert!(len <= self.len(), "range out of bounds");
98        let data =
99            unsafe { core::slice::from_raw_parts(self.handle.as_ptr().cast::<T>().as_ptr(), len) };
100        f(data)
101    }
102
103    pub fn to_vec_cpu(&self) -> Vec<T> {
104        let mut vec: Vec<T> = Vec::with_capacity(self.len());
105        unsafe {
106            let src_ptr = self.handle.as_ptr().as_ptr().cast::<T>();
107            let dst_ptr = vec.as_mut_ptr();
108            dst_ptr.copy_from_nonoverlapping(src_ptr, self.len());
109            vec.set_len(self.len());
110        }
111        vec
112    }
113
114    pub fn prepare_for_device(&self, range: Range<usize>) {
115        self.check_range(&range);
116        self.device
117            .sync_map_for_device(&self.handle, range.start, range.len(), self.direction);
118    }
119
120    pub fn complete_for_cpu(&self, range: Range<usize>) {
121        self.check_range(&range);
122        self.device
123            .sync_map_for_cpu(&self.handle, range.start, range.len(), self.direction);
124    }
125
126    pub fn write_for_device<R>(&mut self, len: usize, f: impl FnOnce(&mut [T]) -> R) -> R {
127        let ret = self.write_with_cpu(len, f);
128        self.prepare_for_device(0..len * core::mem::size_of::<T>());
129        ret
130    }
131
132    pub fn read_from_device<R>(&self, len: usize, f: impl FnOnce(&[T]) -> R) -> R {
133        self.complete_for_cpu(0..len * core::mem::size_of::<T>());
134        self.read_with_cpu(len, f)
135    }
136
137    pub fn bounce_ptr(&self) -> Option<NonNull<u8>> {
138        self.handle.bounce_ptr()
139    }
140
141    fn check_range(&self, range: &Range<usize>) {
142        assert!(
143            range.start <= range.end && range.end <= self.bytes_len(),
144            "range out of bounds, range: {:?}, bytes_len: {}",
145            range,
146            self.bytes_len()
147        );
148    }
149}
150
151impl<T: DmaPod> Drop for StreamingMap<T> {
152    fn drop(&mut self) {
153        unsafe {
154            self.device.unmap_streaming(self.handle);
155        }
156    }
157}