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
use core::ffi::c_void;
use std::boxed::Box;
use std::os::raw::c_ulong;
use std::ptr;
use std::slice;
use std::time::Duration;

use crate::*;

struct RingBufferCallback<'a> {
    cb: Box<dyn FnMut(&[u8]) -> i32 + 'a>,
}

impl<'a> RingBufferCallback<'a> {
    fn new<F>(cb: F) -> Self
    where
        F: FnMut(&[u8]) -> i32 + 'a,
    {
        RingBufferCallback { cb: Box::new(cb) }
    }
}

/// Builds [`RingBuffer`] instances.
///
/// `ringbuf`s are a special kind of [`Map`], used to transfer data between
/// [`Program`]s and userspace.  As of Linux 5.8, the `ringbuf` map is now
/// preferred over the `perf buffer`.
#[derive(Default)]
pub struct RingBufferBuilder<'a> {
    fd_callbacks: Vec<(i32, RingBufferCallback<'a>)>,
}

impl<'a> RingBufferBuilder<'a> {
    pub fn new() -> Self {
        RingBufferBuilder {
            fd_callbacks: vec![],
        }
    }

    /// Add a new ringbuf `map` and associated `callback` to this ring buffer
    /// manager. The callback should take one argument, a slice of raw bytes,
    /// and return an i32.
    ///
    /// Non-zero return values in the callback will stop ring buffer consumption early.
    ///
    /// The callback provides a raw byte slice. You may find libraries such as
    /// [`plain`](https://crates.io/crates/plain) helpful.
    pub fn add<NewF>(&mut self, map: &Map, callback: NewF) -> Result<&mut Self>
    where
        NewF: FnMut(&[u8]) -> i32 + 'a,
    {
        if map.map_type() != MapType::RingBuf {
            return Err(Error::InvalidInput("Must use a RingBuf map".into()));
        }
        self.fd_callbacks
            .push((map.fd(), RingBufferCallback::new(callback)));
        Ok(self)
    }

    /// Build a new [`RingBuffer`]. Must have added at least one ringbuf.
    pub fn build(self) -> Result<RingBuffer<'a>> {
        let mut cbs = vec![];
        let mut ptr: *mut libbpf_sys::ring_buffer = ptr::null_mut();
        let c_sample_cb: libbpf_sys::ring_buffer_sample_fn = Some(Self::call_sample_cb);

        for (fd, callback) in self.fd_callbacks {
            let sample_cb_ptr = Box::into_raw(Box::new(callback));
            if ptr.is_null() {
                // Allocate a new ringbuf manager and add a ringbuf to it
                ptr = unsafe {
                    libbpf_sys::ring_buffer__new(
                        fd,
                        c_sample_cb,
                        sample_cb_ptr as *mut _,
                        std::ptr::null_mut(),
                    )
                };

                // Handle errors
                let err = unsafe { libbpf_sys::libbpf_get_error(ptr as *const _) };
                if err != 0 {
                    return Err(Error::System(err as i32));
                }
            } else {
                // Add a ringbuf to the existing ringbuf manager
                let err = unsafe {
                    libbpf_sys::ring_buffer__add(ptr, fd, c_sample_cb, sample_cb_ptr as *mut _)
                };

                // Handle errors
                if err != 0 {
                    return Err(Error::System(err as i32));
                }
            }

            unsafe { cbs.push(Box::from_raw(sample_cb_ptr)) };
        }

        if ptr.is_null() {
            return Err(Error::InvalidInput(
                "You must add at least one ring buffer map and callback before building".into(),
            ));
        }

        Ok(RingBuffer { ptr, _cbs: cbs })
    }

    unsafe extern "C" fn call_sample_cb(ctx: *mut c_void, data: *mut c_void, size: c_ulong) -> i32 {
        let callback_struct = ctx as *mut RingBufferCallback;
        let callback = (*callback_struct).cb.as_mut();

        callback(slice::from_raw_parts(data as *const u8, size as usize))
    }
}

/// The canonical interface for managing a collection of `ringbuf` maps.
///
/// `ringbuf`s are a special kind of [`Map`], used to transfer data between
/// [`Program`]s and userspace.  As of Linux 5.8, the `ringbuf` map is now
/// preferred over the `perf buffer`.
pub struct RingBuffer<'a> {
    ptr: *mut libbpf_sys::ring_buffer,
    #[allow(clippy::vec_box)]
    _cbs: Vec<Box<RingBufferCallback<'a>>>,
}

impl<'a> RingBuffer<'a> {
    /// Poll from all open ring buffers, calling the registered callback for
    /// each one. Polls continually until we either run out of events to consume
    /// or `timeout` is reached.
    pub fn poll(&self, timeout: Duration) -> Result<()> {
        assert!(!self.ptr.is_null());

        let ret = unsafe { libbpf_sys::ring_buffer__poll(self.ptr, timeout.as_millis() as i32) };

        util::parse_ret(ret)
    }

    /// Greedily consume from all open ring buffers, calling the registered
    /// callback for each one. Consumes continually until we run out of events
    /// to consume or one of the callbacks returns a non-zero integer.
    pub fn consume(&self) -> Result<()> {
        assert!(!self.ptr.is_null());

        let ret = unsafe { libbpf_sys::ring_buffer__consume(self.ptr) };

        util::parse_ret(ret)
    }
}

impl<'a> Drop for RingBuffer<'a> {
    fn drop(&mut self) {
        unsafe {
            if !self.ptr.is_null() {
                libbpf_sys::ring_buffer__free(self.ptr);
            }
        }
    }
}