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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/*
 * TODO: reuse buffers.
 */

use std::cell::RefCell;
use std::io;
use std::io::{
    Error,
    ErrorKind,
};
use std::os::unix::io::{AsRawFd, RawFd};
use std::ptr;
use std::rc::Rc;
use std::u64;

use crate::aio::slab::Slab;

const MAX_EVENTS: usize = 100; // TODO: tweak this value.

#[repr(u32)]
pub enum Mode {
    Read = ffi::EPOLLIN | ffi::EPOLLEXCLUSIVE,
    ReadWrite = ffi::EPOLLIN | ffi::EPOLLOUT | ffi::EPOLLEXCLUSIVE,
    Write = ffi::EPOLLOUT | ffi::EPOLLEXCLUSIVE,
}

trait FnBox {
    fn call_box(self: Box<Self>, event: ffi::epoll_event);
}

impl<T> FnBox for T where T: FnOnce(ffi::epoll_event) {
    fn call_box(self: Box<Self>, event: ffi::epoll_event) {
        (*self)(event);
    }
}

enum Callback {
    Empty,
    Normal(Box<dyn FnMut(ffi::epoll_event) -> Action>),
    Oneshot(Box<dyn FnBox>),
}

#[derive(PartialEq)]
pub enum Action {
    Continue,
    Stop,
}

pub struct Event {
    callback_entry: usize,
    event_loop: EventLoop,
}

impl Event {
    fn new(callback_entry: usize, event_loop: &EventLoop) -> Self {
        Self {
            callback_entry,
            event_loop: event_loop.clone(),
        }
    }

    pub fn set_callback<F>(self, callback: F)
    where F: FnMut(ffi::epoll_event) -> Action + 'static,
    {
        self.event_loop.callbacks.borrow_mut()[self.callback_entry] = Callback::Normal(Box::new(callback));
    }
}

pub struct EventOnce {
    callback_entry: usize,
    event_loop: EventLoop,
}

impl EventOnce {
    fn new(callback_entry: usize, event_loop: EventLoop) -> Self {
        Self {
            callback_entry,
            event_loop: event_loop.clone(),
        }
    }

    pub fn set_callback<F>(self, callback: F)
    where F: FnOnce(ffi::epoll_event) + 'static,
    {
        self.event_loop.callbacks.borrow_mut()[self.callback_entry] = Callback::Oneshot(Box::new(callback));
    }
}

pub enum EpollResult {
    Error(io::Error),
    Interrupted,
    Ok,
}

thread_local! {
    static EVENT_FD: RawFd = unsafe { ffi::eventfd(0, ffi::EFD_NONBLOCK) };
}

#[derive(Clone)]
pub struct EventLoop {
    callbacks: Rc<RefCell<Slab<Callback>>>,
    fd: RawFd,
    stopped: bool,
}

impl EventLoop {
    pub fn new() -> io::Result<Self> {
        let fd = unsafe { ffi::epoll_create1(0) };
        if fd == -1 {
            return Err(Error::last_os_error());
        }
        let event_loop = Self {
            callbacks: Rc::new(RefCell::new(Slab::new())),
            fd,
            stopped: false,
        };

        let event_fd = EVENT_FD.with(|&event_fd| event_fd);
        event_loop.add_raw_fd_without_callback(event_fd, Mode::Read)?;

        Ok(event_loop)
    }

    fn add_raw_fd_without_callback(&self, fd: RawFd, mode: Mode) -> io::Result<()> {
        let mut event = ffi::epoll_event {
            events: mode as u32,
            data: ffi::epoll_data_t {
                u64: u64::MAX,
            },
        };
        if unsafe { ffi::epoll_ctl(self.fd, ffi::EpollOperation::Add, fd, &mut event) } == -1 {
            return Err(Error::last_os_error());
        }
        Ok(())
    }

    pub fn add_raw_fd<F>(&self, fd: RawFd, mode: Mode, callback: F) -> io::Result<()>
    where F: FnMut(ffi::epoll_event) -> Action + 'static,
    {
        let callback_entry = self.callbacks.borrow_mut().insert(Callback::Normal(Box::new(callback)));
        let mut event = ffi::epoll_event {
            events: mode as u32,
            data: ffi::epoll_data_t {
                u64: callback_entry as u64,
            },
        };
        if unsafe { ffi::epoll_ctl(self.fd, ffi::EpollOperation::Add, fd, &mut event) } == -1 {
            // TODO: should probably deallocate memory here.
            return Err(Error::last_os_error());
        }
        Ok(())
    }

    pub fn add_raw_fd_oneshot<F>(&self, fd: RawFd, mode: Mode, callback: F) -> io::Result<()>
    where F: FnOnce(ffi::epoll_event) + 'static,
    {
        let callback_entry = self.callbacks.borrow_mut().insert(Callback::Oneshot(Box::new(callback)));
        let mut event = ffi::epoll_event {
            events: mode as u32 & !ffi::EPOLLEXCLUSIVE | ffi::EPOLLONESHOT,
            data: ffi::epoll_data_t {
                u64: callback_entry as u64,
            },
        };
        if unsafe { ffi::epoll_ctl(self.fd, ffi::EpollOperation::Add, fd, &mut event) } == -1 {
            // TODO: should probably deallocate memory here.
            return Err(Error::last_os_error());
        }
        Ok(())
    }

    pub fn remove_fd<A: AsRawFd>(&self, as_fd: &A) -> io::Result<()> {
        self.remove_raw_fd(as_fd.as_raw_fd())
    }

    pub fn remove_raw_fd(&self, fd: RawFd) -> io::Result<()> {
        if unsafe { ffi::epoll_ctl(self.fd, ffi::EpollOperation::Delete, fd, ptr::null_mut()) } == -1 {
            return Err(Error::last_os_error());
        }
        Ok(())
    }

    pub fn try_add_raw_fd(&self, fd: RawFd, mode: Mode) -> io::Result<Event> {
        let callback_entry = self.callbacks.borrow_mut().insert(Callback::Empty);
        let mut event = ffi::epoll_event {
            events: mode as u32,
            data: ffi::epoll_data_t {
                u64: callback_entry as u64,
            },
        };
        if unsafe { ffi::epoll_ctl(self.fd, ffi::EpollOperation::Add, fd, &mut event) } == -1 {
            // TODO: should probably deallocate memory here.
            return Err(Error::last_os_error());
        }
        Ok(Event::new(callback_entry, self))
    }

    pub fn try_add_raw_fd_oneshot(&self, fd: RawFd, mode: Mode) -> io::Result<EventOnce> {
        let callback_entry = self.callbacks.borrow_mut().insert(Callback::Empty);
        let mut event = ffi::epoll_event {
            events: mode as u32 & !ffi::EPOLLEXCLUSIVE | ffi::EPOLLONESHOT,
            data: ffi::epoll_data_t {
                u64: callback_entry as u64,
            },
        };
        if unsafe { ffi::epoll_ctl(self.fd, ffi::EpollOperation::Add, fd, &mut event) } == -1 {
            // TODO: should probably deallocate memory here.
            return Err(Error::last_os_error());
        }
        Ok(EventOnce::new(callback_entry, self.clone()))
    }

    pub fn iterate(&self, event_list: &mut [ffi::epoll_event]) -> EpollResult {
        let epoll_fd = self.fd;

        let ready = unsafe { ffi::epoll_wait(epoll_fd, event_list.as_mut_ptr(), event_list.len() as i32, -1) };
        if ready == -1 {
            let last_error = Error::last_os_error();
            if last_error.kind() == ErrorKind::Interrupted {
                return EpollResult::Interrupted;
            }
            else {
                return EpollResult::Error(last_error);
            }
        }

        for &event in event_list.iter().take(ready as usize) {
            unsafe {
                if event.data.u64 == u64::MAX {
                    // No callback is associated with the eventfd used to wakeup the event loop.
                    EVENT_FD.with(|&event_fd| {
                        let mut value = 0u64;
                        ffi::eventfd_read(event_fd, &mut value as *mut _)
                    });
                    continue;
                }
            }
            let entry = unsafe { event.data.u64 as usize };
            // NOTE: Remove the callback because callbacks can be added in the update() method.
            let callback = std::mem::replace(&mut self.callbacks.borrow_mut()[entry], Callback::Empty);
            let callback =
                match callback {
                    Callback::Empty => panic!("callback should not be empty"),
                    Callback::Normal(mut callback) => {
                        if callback(event) == Action::Stop {
                            None
                        }
                        else {
                            Some(Callback::Normal(callback))
                        }
                    },
                    Callback::Oneshot(callback) => {
                        let callback: Box<_> = callback;
                        callback.call_box(event);
                        None
                    },
                };
            if let Some(callback) = callback {
                self.callbacks.borrow_mut()[entry] = callback;
            }
        }

        EpollResult::Ok
    }

    pub fn run(&self) -> io::Result<()> {
        let mut event_list = event_list();

        while !self.stopped {
            match self.iterate(&mut event_list) {
                // Restart if interrupted by signal.
                EpollResult::Interrupted => continue,
                EpollResult::Error(error) => return Err(error),
                EpollResult::Ok => (),
            }
        }

        Ok(())
    }

    pub fn stop(&mut self) {
        self.stopped = true;
        EventLoop::wakeup();
    }

    pub fn wakeup() {
        // TODO: only wake up if currently blocking?
        EVENT_FD.with(|&event_fd| {
            unsafe {
                ffi::eventfd_write(event_fd, 1);
            }
        });
    }
}

pub fn event_list() -> [ffi::epoll_event; MAX_EVENTS] {
    [
        ffi::epoll_event {
            events: 0,
            data: ffi::epoll_data_t {
                u32: 0,
            }
        }; MAX_EVENTS
    ]
}

pub mod ffi {
    use std::os::raw::c_void;

    #[repr(i32)]
    pub enum EpollOperation {
        Add = 1,
        Delete = 2,
        Modify = 3,
    }

    pub const EPOLLIN: u32 = 0x001;
    pub const EPOLLOUT: u32 = 0x004;
    pub const EPOLLERR: u32 = 0x008;
    pub const EPOLLONESHOT: u32 = 1 << 30;
    pub const EPOLLHUP: u32 = 0x010;
    pub const EFD_NONBLOCK: i32 = 0o4000;
    pub const EPOLLEXCLUSIVE: u32 = 1 << 28;

   #[repr(C)]
    #[derive(Clone, Copy)]
    pub union epoll_data_t {
        pub ptr: *mut c_void,
        pub fd: i32,
        pub u32: u32,
        pub u64: u64,
    }

    #[repr(C, packed)]
    #[derive(Clone, Copy)]
    pub struct epoll_event {
        pub events: u32,
        pub data: epoll_data_t,
    }

    #[allow(non_camel_case_types)]
    type eventfd_t = u64;

    extern "C" {
        pub fn epoll_create1(flags: i32) -> i32;
        pub fn epoll_ctl(epfd: i32, op: EpollOperation, fd: i32, event: *mut epoll_event) -> i32;
        pub fn epoll_wait(epdf: i32, events: *mut epoll_event, maxevents: i32, timeout: i32) -> i32;

        pub fn eventfd(initval: u32, flags: i32) -> i32;
        pub fn eventfd_read(fd: i32, value: *mut eventfd_t) -> i32;
        pub fn eventfd_write(fd: i32, value: eventfd_t) -> i32;
    }
}