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
use std::os::unix::io::RawFd;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::Duration;
use std::{io, ptr};
use super::{timeout_handler, EventData, IoData, TimerList};
use crate::coroutine_impl::run_coroutine;
use crate::scheduler::get_scheduler;
use crate::std::queue::seg_queue::SegQueue as mpsc;
use crate::timeout_list::{now, ns_to_dur};
pub type SysEvent = libc::kevent;
// used for notify wakeup
const NOTIFY_IDENT: usize = 42;
macro_rules! kevent {
($id:expr, $filter:expr, $flags:expr, $data:expr) => {
libc::kevent {
ident: $id as libc::uintptr_t,
filter: $filter,
flags: $flags,
fflags: 0,
data: 0,
udata: $data as *mut _,
}
};
}
struct SingleSelector {
kqfd: RawFd,
timer_list: TimerList,
free_ev: mpsc<Arc<EventData>>,
}
impl SingleSelector {
pub fn new() -> io::Result<Self> {
let kqfd = unsafe { libc::kqueue() };
if kqfd < 0 {
return Err(io::Error::last_os_error());
}
let kev = libc::kevent {
ident: NOTIFY_IDENT,
filter: libc::EVFILT_USER,
flags: libc::EV_ADD | libc::EV_CLEAR,
fflags: 0,
data: 0,
udata: ptr::null_mut(),
};
let ret = unsafe { libc::kevent(kqfd, &kev, 1, ptr::null_mut(), 0, ptr::null()) };
if ret < 0 {
return Err(io::Error::last_os_error());
}
Ok(SingleSelector {
kqfd: kqfd,
free_ev: mpsc::new(),
timer_list: TimerList::new(),
})
}
}
impl Drop for SingleSelector {
fn drop(&mut self) {
let _ = unsafe { libc::close(self.kqfd) };
}
}
pub struct Selector {
vec: Vec<SingleSelector>,
}
impl Selector {
pub fn new(io_workers: usize) -> io::Result<Self> {
let mut s = Selector {
vec: Vec::with_capacity(io_workers),
};
for _ in 0..io_workers {
let ss = SingleSelector::new()?;
s.vec.push(ss);
}
Ok(s)
}
pub fn select(
&self,
id: usize,
events: &mut [SysEvent],
timeout: Option<u64>,
) -> io::Result<Option<u64>> {
let timeout = timeout.map(|to| {
let dur = ns_to_dur(to);
libc::timespec {
tv_sec: dur.as_secs() as libc::time_t,
tv_nsec: dur.subsec_nanos() as libc::c_long,
}
});
let timeout = timeout
.as_ref()
.map(|s| s as *const _)
.unwrap_or(ptr::null_mut());
// //info!("select; timeout={:?}", timeout_ms);
let mask = self.vec.len() + id;
let single_selector = unsafe { self.vec.get_unchecked(id) };
// first register thread handle
let scheduler = get_scheduler();
scheduler
.workers
.parked
.fetch_or(mask as u64, Ordering::Relaxed);
// Wait for epoll events for at most timeout_ms milliseconds
let kqfd = single_selector.kqfd;
let n = unsafe {
libc::kevent(
kqfd,
ptr::null(),
0,
events.as_mut_ptr(),
events.len() as libc::c_int,
timeout,
)
};
// clear the park stat after comeback
scheduler
.workers
.parked
.fetch_and((mask - self.vec.len()) as u64, Ordering::Relaxed);
if n < 0 {
return Err(io::Error::last_os_error());
}
let n = n as usize;
for event in events[..n].iter() {
if event.udata == ptr::null_mut() {
// this is just a wakeup event, ignore it
// let mut buf = [0u8; 8];
// clear the eventfd, ignore the result
// read(self.vec[id].evfd, &mut buf).ok();
//info!("got wakeup event in select, id={}", id);
continue;
}
let data = unsafe { &mut *(event.udata as *mut EventData) };
// //info!("select got event, data={:p}", data);
data.io_flag.store(true, Ordering::Release);
// first check the atomic co, this may be grab by the worker first
let co = match data.co.take() {
None => continue,
Some(co) => co,
};
co.prefetch();
// it's safe to remove the timer since we are running the timer_list in the same thread
data.timer.borrow_mut().take().map(|h| {
unsafe {
// tell the timer handler not to cancel the io
// it's not always true that you can really remove the timer entry
h.with_mut_data(|value| value.data.event_data = ptr::null_mut());
}
h.remove()
});
// schedule the coroutine
run_coroutine(co);
}
// run all the local tasks
scheduler.run_queued_tasks(id);
// free the unused event_data
self.free_unused_event_data(id);
// deal with the timer list
let next_expire = single_selector
.timer_list
.schedule_timer(now(), &timeout_handler);
Ok(next_expire)
}
// this will post an os event so that we can wakeup the event loop
#[inline]
pub fn wakeup(&self, id: usize) {
let kqfd = unsafe { self.vec.get_unchecked(id) }.kqfd;
let kev = libc::kevent {
ident: NOTIFY_IDENT,
filter: libc::EVFILT_USER,
flags: 0,
fflags: libc::NOTE_TRIGGER,
data: 0,
udata: ptr::null_mut(),
};
let _ = unsafe { libc::kevent(kqfd, &kev, 1, ptr::null_mut(), 0, ptr::null()) };
//info!("wakeup id={:?}, ret={:?}", id, ret);
}
// register io event to the selector
#[inline]
pub fn add_fd(&self, io_data: IoData) -> io::Result<IoData> {
let fd = io_data.fd;
let id = fd as usize % self.vec.len();
let kqfd = unsafe { self.vec.get_unchecked(id) }.kqfd;
//info!("add fd to kqueue select, fd={:?}", fd);
let flags = libc::EV_ADD | libc::EV_CLEAR;
let udata = io_data.as_ref() as *const _;
let changes = [
kevent!(fd, libc::EVFILT_READ, flags, udata),
kevent!(fd, libc::EVFILT_WRITE, flags, udata),
];
let n = unsafe {
libc::kevent(
kqfd,
changes.as_ptr(),
changes.len() as libc::c_int,
ptr::null_mut(),
0,
ptr::null(),
)
};
if n < 0 {
return Err(io::Error::last_os_error());
}
Ok(io_data)
}
#[inline]
pub fn del_fd(&self, io_data: &IoData) {
use std::ops::Deref;
io_data.timer.borrow_mut().take().map(|h| {
unsafe {
// mark the timer as removed if any, this only happened
// when cancel an IO. what if the timer expired at the same time?
// because we run this func in the user space, so the timer handler
// will not got the coroutine
h.with_mut_data(|value| value.data.event_data = ptr::null_mut());
}
});
let fd = io_data.fd;
let id = fd as usize % self.vec.len();
let single_selector = unsafe { self.vec.get_unchecked(id) };
let kqfd = single_selector.kqfd;
//info!("del fd from kqueue select, fd={:?}", fd);
let filter = libc::EV_DELETE;
let changes = [
kevent!(fd, libc::EVFILT_READ, filter, ptr::null_mut()),
kevent!(fd, libc::EVFILT_WRITE, filter, ptr::null_mut()),
];
// ignore the error
unsafe {
libc::kevent(
kqfd,
changes.as_ptr(),
changes.len() as libc::c_int,
ptr::null_mut(),
0,
ptr::null(),
);
}
// after EpollCtlDel push the unused event data
single_selector.free_ev.push(io_data.deref().clone());
}
// we can't free the event data directly in the worker thread
// must free them before the next epoll_wait
#[inline]
fn free_unused_event_data(&self, id: usize) {
let free_ev = &unsafe { self.vec.get_unchecked(id) }.free_ev;
while free_ev.pop().is_some() {}
}
// register the io request to the timeout list
#[inline]
pub fn add_io_timer(&self, io: &IoData, timeout: Duration) {
let id = io.fd as usize % self.vec.len();
// //info!("io timeout = {:?}", dur);
let (h, b_new) = unsafe { self.vec.get_unchecked(id) }
.timer_list
.add_timer(timeout, io.timer_data());
if b_new {
// wakeup the event loop thread to recall the next wait timeout
self.wakeup(id);
}
io.timer.borrow_mut().replace(h);
}
}