1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// Copyright 2020-2021, Cerno
// Licensed under the MIT License
// See the LICENSE file or <http://opensource.org/licenses/MIT>

#![doc = include_str!("../README.md")]
#![warn(missing_debug_implementations)]
#![warn(missing_docs)]
#![warn(rust_2018_idioms)]
#![deny(clippy::all)]
#![deny(clippy::pedantic)]
#![deny(clippy::cargo)]

use std::{
    convert::TryInto,
    os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd, RawFd},
};

use ioctl::{
    dma_buf_begin_cpu_read_access, dma_buf_begin_cpu_readwrite_access,
    dma_buf_begin_cpu_write_access, dma_buf_end_cpu_read_access, dma_buf_end_cpu_readwrite_access,
    dma_buf_end_cpu_write_access,
};
use log::debug;
use memmap::MmapMut;
use nix::sys::stat::fstat;

mod ioctl;

/// Error type to map a [`DmaBuf`]
#[derive(thiserror::Error, Debug)]
pub enum MapError {
    /// An Error occured while accessing the buffer file descriptor
    #[error("Could not access the buffer file descriptor: {reason}")]
    FdAccess {
        /// Description of the Error
        reason: String,

        /// Source of the Error
        source: std::io::Error,
    },

    /// An Error occured while mapping the buffer file descriptor
    #[error("Could not map the buffer file descriptor: {reason}")]
    MappingFailed {
        /// Description of the Error
        reason: String,

        /// Source of the Error
        source: std::io::Error,
    },
}

/// A DMA-Buf buffer
#[derive(Debug)]
pub struct DmaBuf {
    fd: OwnedFd,
}

impl DmaBuf {
    /// Maps a `DmaBuf` for the CPU to access it
    ///
    /// # Panics
    ///
    /// If the buffer size reported by the kernel (`i64`) cannot fit into an `usize`.
    ///
    /// # Errors
    ///
    /// Will return an error if either the Buffer's length can't be retrieved, or if the mmap call
    /// fails.
    pub fn memory_map(self) -> Result<MappedDmaBuf, MapError> {
        let raw_fd = self.as_raw_fd();

        debug!("Mapping DMA-Buf buffer with File Descriptor {:#?}", self.fd);

        let stat = fstat(raw_fd).map_err(|e| MapError::FdAccess {
            reason: e.to_string(),
            source: std::io::Error::from(e),
        })?;

        let len = stat.st_size.try_into().unwrap();
        debug!("Valid buffer, size {}", len);

        let mmap = unsafe { MmapMut::map_mut(raw_fd) }.map_err(|e| MapError::MappingFailed {
            reason: e.to_string(),
            source: e,
        })?;

        debug!("Memory Mapping Done");

        Ok(MappedDmaBuf {
            buf: self,
            len,
            mmap,
        })
    }
}

/// A `DmaBuf` mapped in memory
pub struct MappedDmaBuf {
    buf: DmaBuf,
    len: usize,
    mmap: MmapMut,
}

/// Error type to access a [`MappedDmaBuf`]
#[derive(Debug, thiserror::Error)]
pub enum BufferError {
    /// An Error occured while accessing the buffer file descriptor
    #[error("Could not access the buffer: {reason}")]
    FdAccess {
        /// Description of the Error
        reason: String,

        /// Source of the Error
        source: std::io::Error,
    },

    /// An Error occured in the closure
    #[error("The closure returned an error: {0}")]
    Closure(Box<dyn std::error::Error>),
}

impl MappedDmaBuf {
    /// Calls a closure to read the buffer content
    ///
    /// DMA-Buf requires the user-space to call the `DMA_BUF_IOCTL_SYNC` ioctl before and after any
    /// CPU access to a buffer in order to maintain the cache coherency. The closure will be run
    /// with those primitives called for a read access from the CPU.
    ///
    /// The result of the closure will be returned.
    ///
    /// # Errors
    ///
    /// Will return [Error] if the underlying ioctl or the closure fails
    pub fn read<A, F, R>(&self, f: F, arg: Option<A>) -> Result<R, BufferError>
    where
        F: Fn(&[u8], Option<A>) -> Result<R, Box<dyn std::error::Error>>,
    {
        let raw_fd = self.as_raw_fd();

        debug!("Preparing the buffer for read access");

        dma_buf_begin_cpu_read_access(raw_fd)?;

        debug!("Accessing the buffer");

        let ret = f(&self.mmap, arg)
            .map(|v| {
                debug!("Closure done without error");
                v
            })
            .map_err(|e| {
                debug!("Closure encountered an error {}", e);
                BufferError::Closure(e)
            });

        dma_buf_end_cpu_read_access(raw_fd)?;

        debug!("Buffer access done");

        ret
    }

    /// Calls a closure to read from and write to the buffer content
    ///
    /// DMA-Buf requires the user-space to call the `DMA_BUF_IOCTL_SYNC` ioctl before and after any
    /// CPU access to a buffer in order to maintain the cache coherency. The closure will be run
    /// with those primitives called for a read and write access from the CPU.
    ///
    /// The result of the closure will be returned on success. On failure, the closure must return
    /// `Error::Closure`
    ///
    /// # Errors
    ///
    /// Will return [Error] if the underlying ioctl or the closure fails
    pub fn readwrite<A, F, R>(&mut self, f: F, arg: Option<A>) -> Result<R, BufferError>
    where
        F: Fn(&mut [u8], Option<A>) -> Result<R, Box<dyn std::error::Error>>,
    {
        let raw_fd = self.as_raw_fd();

        debug!("Preparing the buffer for read/write access");

        dma_buf_begin_cpu_readwrite_access(raw_fd)?;

        debug!("Accessing the buffer");

        let ret = f(&mut self.mmap, arg)
            .map(|v| {
                debug!("Closure done without error");
                v
            })
            .map_err(|e| {
                debug!("Closure encountered an error {}", e);
                BufferError::Closure(e)
            });

        dma_buf_end_cpu_readwrite_access(raw_fd)?;

        debug!("Buffer access done");

        ret
    }

    /// Calls a closure to read from and write to the buffer content
    ///
    /// DMA-Buf requires the user-space to call the `DMA_BUF_IOCTL_SYNC` ioctl before and after any
    /// CPU access to a buffer in order to maintain the cache coherency. The closure will be run
    /// with those primitives called for a read and write access from the CPU.
    ///
    /// The closure must return () on success. On failure, the closure must return `Error::Closure`.
    ///
    /// # Errors
    ///
    /// Will return [Error] if the underlying ioctl or the closure fails
    pub fn write<A, F>(&mut self, f: F, arg: Option<A>) -> Result<(), BufferError>
    where
        F: Fn(&mut [u8], Option<A>) -> Result<(), Box<dyn std::error::Error>>,
    {
        let raw_fd = self.as_raw_fd();

        debug!("Preparing the buffer for write access");

        dma_buf_begin_cpu_write_access(raw_fd)?;

        debug!("Accessing the buffer");

        let ret = f(&mut self.mmap, arg)
            .map(|()| {
                debug!("Closure done without error");
            })
            .map_err(|e| {
                debug!("Closure encountered an error {}", e);
                BufferError::Closure(e)
            });

        dma_buf_end_cpu_write_access(raw_fd)?;

        debug!("Buffer access done");

        ret
    }
}

impl From<OwnedFd> for DmaBuf {
    fn from(owned: OwnedFd) -> Self {
        unsafe { Self::from_raw_fd(owned.into_raw_fd()) }
    }
}

impl std::os::unix::io::AsRawFd for DmaBuf {
    fn as_raw_fd(&self) -> RawFd {
        self.fd.as_raw_fd()
    }
}

impl std::os::unix::io::AsRawFd for MappedDmaBuf {
    fn as_raw_fd(&self) -> RawFd {
        self.buf.as_raw_fd()
    }
}

impl std::os::unix::io::FromRawFd for DmaBuf {
    unsafe fn from_raw_fd(fd: RawFd) -> Self {
        debug!("Importing DMABuf from File Descriptor {}", fd);
        Self {
            fd: OwnedFd::from_raw_fd(fd),
        }
    }
}

impl std::fmt::Debug for MappedDmaBuf {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MappedDmaBuf")
            .field("DmaBuf", &self.buf)
            .field("len", &self.len)
            .field("address", &self.mmap.as_ptr())
            .finish()
    }
}