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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
use dma_buf::DmaBuf;
use parking_lot::{ArcRwLockWriteGuard, RwLock, RawRwLock};
use std::fmt;
use std::{io, mem};
use std::ops;
use std::os::fd::{FromRawFd, OwnedFd};
use std::sync::Arc;
use tracing::error;

use crate::buffer;
use crate::device::Handle;
use crate::memory::Memory;
use crate::v4l2;
use crate::v4l_sys::{v4l2_format, v4l2_requestbuffers, v4l2_exportbuffer};


/// An entry corresponding to a DMA-BUF buffer.
pub trait EntryBuffer {
    fn from_owned_fd(fd: OwnedFd) -> Self;
}

impl EntryBuffer for DmaBuf {
    fn from_owned_fd(fd: OwnedFd) -> Self {
        fd.into()
    }
}

/// Allows different implementations of release to be used by the generic Drop
pub trait DmabufRelease {
    fn release(&mut self) -> io::Result<()>;
}

/// Manage dmabuf buffers
///
/// All buffers are released in the Drop impl.
pub struct Arena<T: EntryBuffer> where Self: DmabufRelease {
    handle: Arc<Handle>,
    bufs: Vec<T>,
    buf_type: buffer::Type,
}

impl<T: EntryBuffer> Arena<T>  where Self: DmabufRelease {
    /// Returns a new buffer manager instance
    ///
    /// You usually do not need to use this directly.
    /// A UserBufferStream creates its own manager instance by default.
    ///
    /// # Arguments
    ///
    /// * `handle` - Device handle to get its file descriptor
    /// * `buf_type` - Type of the buffers
    pub fn new(handle: Arc<Handle>, buf_type: buffer::Type) -> Self {
        Arena {
            handle,
            bufs: Vec::new(),
            buf_type,
        }
    }

    fn requestbuffers_desc(&self) -> v4l2_requestbuffers {
        v4l2_requestbuffers {
            type_: self.buf_type as u32,
            ..unsafe { mem::zeroed() }
        }
    }

    /// Returns the number of buffers present in the arena (same as the number in `self.bufs`).
    pub fn allocate(&mut self, count: u32) -> io::Result<u32> {
        // we need to get the maximum buffer size from the format first
        let mut v4l2_fmt = v4l2_format {
            type_: self.buf_type as u32,
            ..unsafe { mem::zeroed() }
        };
        unsafe {
            v4l2::ioctl(
                self.handle.fd(),
                v4l2::vidioc::VIDIOC_G_FMT,
                &mut v4l2_fmt as *mut _ as *mut std::os::raw::c_void,
            )?;
        }

        let mut v4l2_reqbufs = v4l2_requestbuffers {
            count,
            memory: Memory::Mmap as u32,
            ..self.requestbuffers_desc()
        };
        unsafe {
            v4l2::ioctl(
                self.handle.fd(),
                v4l2::vidioc::VIDIOC_REQBUFS,
                &mut v4l2_reqbufs as *mut _ as *mut std::os::raw::c_void,
            )?;
        }

        for index in 0..v4l2_reqbufs.count {
            let mut v4l2_exportbuf = v4l2_exportbuffer {
                index,
                type_: self.buf_type as u32,
                flags: libc::O_RDWR as _,
                ..unsafe { mem::zeroed() }
            };
            let fd = unsafe {
                v4l2::ioctl(
                    self.handle.fd(),
                    v4l2::vidioc::VIDIOC_EXPBUF,
                    &mut v4l2_exportbuf as *mut _ as *mut std::os::raw::c_void,
                )?;
                OwnedFd::from_raw_fd(v4l2_exportbuf.fd)
            };
            self.bufs.push(T::from_owned_fd(fd));
        }
        
        let mut v4l2_reqbufs = v4l2_requestbuffers {
            count,
            memory: Memory::DmaBuf as u32,
            ..self.requestbuffers_desc()
        };
        unsafe {
            v4l2::ioctl(
                self.handle.fd(),
                v4l2::vidioc::VIDIOC_REQBUFS,
                &mut v4l2_reqbufs as *mut _ as *mut std::os::raw::c_void,
            )?;
        }
        
        Ok(v4l2_reqbufs.count)
    }

    pub fn len(&self) -> usize {
        self.bufs.len()
    }
}

impl Arena<DmaBuf> {
    /// Returns the buffer for this index
    pub fn get_dmabuf(&mut self, index: usize) -> Result<&DmaBuf, &'static str> {
        self.bufs.get(index)
            .ok_or("Index higher than available buffers")
    }
    
    /// Returns the buffer for this index
    pub fn get_dmabuf_mut(&mut self, index: usize) -> Result<&mut DmaBuf, &'static str> {
        self.bufs.get_mut(index)
            .ok_or("Index higher than available buffers")
    }
}

impl DmabufRelease for Arena<DmaBuf> {
    fn release(&mut self) -> io::Result<()> {
        // free all buffers by requesting 0
        let mut v4l2_reqbufs = v4l2_requestbuffers {
            count: 0,
            memory: Memory::DmaBuf as u32,
            ..self.requestbuffers_desc()
        };
        unsafe {
            v4l2::ioctl(
                self.handle.fd(),
                v4l2::vidioc::VIDIOC_REQBUFS,
                &mut v4l2_reqbufs as *mut _ as *mut std::os::raw::c_void,
            )
        }
    }
}

/// A DMA-BUF buffer which is handed out to the user as if owned, but cannot be accessed while it's enqueued at the device for writing.
///
/// Watch out for deadlocks!
#[derive(Clone)]
pub struct DmaBufProtected(Arc<RwLock<DmaBuf>>);

impl ops::Deref for DmaBufProtected {
    type Target = Arc<RwLock<DmaBuf>>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl fmt::Debug for DmaBufProtected {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("DmaBufProtected")
            .field(&self.0.data_ptr())
            .finish()
    }
}

pub struct EntryDmaBufProtected {
    /// This serves as a stable identifier of a buffer corresponding to this slot, meaning a buffer with this ID has the same index known by the kernel and the same device.
    id: *mut DmaBuf,
    /// The buffer which may be handed out to the user after it's ready.
    /// RwLock locked for writing ensures no other reference can try to use it while it's waiting to be filled.
    buf: Option<ArcRwLockWriteGuard<RawRwLock, DmaBuf>>,
}

impl EntryBuffer for EntryDmaBufProtected {
    fn from_owned_fd(fd: OwnedFd) -> Self {
        let buf = Arc::new(RwLock::new(DmaBuf::from(fd)));
        Self {
            id: buf.data_ptr(),
            buf: Some(buf.write_arc()),
        }
    }
}


impl fmt::Debug for EntryDmaBufProtected {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("EntryDmaBufProtected")
            .field(&self.id)
            .field(&self.buf.as_ref().map(|_| ()))
            .finish()
    }
}

/// Allows the user to manage buffers manually. Buffers must be explicitly replaced. Release will only succeed if all buffers were returned with replace_buffer.
pub type ManuallyManaged = Arena<EntryDmaBufProtected>;

impl ManuallyManaged {
    /// Finds the kernel index for this buffer and places it there.
    /// Doesn't check if the buffer was there already. Returns the kernel index.
    pub fn replace_buffer(&mut self, buf: DmaBufProtected) -> Result<usize, (DmaBufProtected, &'static str)> {
        let index = self.bufs.iter().position(|entry| entry.id == buf.0.data_ptr());

        match index {
            None => Err((buf, "Buffer not from this stream")),
            Some(index) => {
                self.bufs[index] = EntryDmaBufProtected {
                    id: buf.0.data_ptr(),
                    buf: Some(buf.0.write_arc()),
                };
                Ok(index)
            }
        }
    }
    
    /// Removes and returns buffer at this kernel index.
    pub fn take_buffer(&mut self, index: usize) -> Result<DmaBufProtected, &'static str> {
        let rw_buf = self.bufs.get_mut(index)
            .ok_or("Index higher than available buffers")?
            .buf.take()
            .ok_or("No buffer was stored at this index")?;

        Ok(DmaBufProtected(ArcRwLockWriteGuard::rwlock(&rw_buf).clone()))
    }

    /// Returns a writeably-locked buffer for this index
    pub fn get_dmabuf_mut(&mut self, index: usize) -> Result<&mut DmaBuf, &'static str> {
        Ok(
            self.bufs.get_mut(index)
                .ok_or("Index higher than available buffers")?
                .buf.as_mut()
                .ok_or("No buffer was stored at this index")?
        )
    }
    
    /// Release buffers without checking if any buffers are gone missing.
    ///
    /// What makes this unsafe is that the buffers out there may become unuseable (TODO: check semantics).
    /// See [V4L2_BUF_CAP_SUPPORTS_ORPHANED_BUFS](https://docs.kernel.org/userspace-api/media/v4l/vidioc-reqbufs.html#description).
    pub unsafe fn force_release(&mut self) -> io::Result<()> {
        // free all buffers by requesting 0
        let mut v4l2_reqbufs = v4l2_requestbuffers {
            count: 0,
            memory: Memory::DmaBuf as u32,
            ..self.requestbuffers_desc()
        };
        unsafe {
            v4l2::ioctl(
                self.handle.fd(),
                v4l2::vidioc::VIDIOC_REQBUFS,
                &mut v4l2_reqbufs as *mut _ as *mut std::os::raw::c_void,
            )
        }
    }
}

impl DmabufRelease for ManuallyManaged {
    fn release(&mut self) -> io::Result<()> {
        let free_buffer = self.bufs.iter()
            .find(|EntryDmaBufProtected { buf, .. }| buf.is_none());
        if let Some(_) = free_buffer {
            return Err(io::Error::other("Busy: not all buffers were returned"));
        }
        
        unsafe { self.force_release() }
    }
}

impl<T: EntryBuffer> Drop for Arena<T> where Self: DmabufRelease {
    fn drop(&mut self) {
        if self.bufs.is_empty() {
            // nothing to do
            return;
        }

        if let Err(e) = self.release() {
            if let Some(code) = e.raw_os_error() {
                // ENODEV means the file descriptor wrapped in the handle became invalid, most
                // likely because the device was unplugged or the connection (USB, PCI, ..)
                // broke down. Handle this case gracefully by ignoring it.
                if code == 19 {
                    /* ignore */
                    return;
                }
            }

            error!("DMABUF leak: {:?}", e);
        }
    }
}