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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! `event` on Linux and fullrust: `ppoll`, in its 64-bit time variant on
//! 32-bit architectures.
//!
//! Constants are those of `include/uapi/asm-generic/poll.h`, which every
//! architecture oscall supports uses.
use core::time::Duration;
use crate::Result;
use crate::event::{Interest, Readiness};
use crate::sys::RawHandle;
use crate::sys::syscall;
use crate::sys::time::Timespec;
const POLLIN: i16 = 0x0001;
const POLLOUT: i16 = 0x0004;
const POLLERR: i16 = 0x0008;
const POLLHUP: i16 = 0x0010;
const POLLNVAL: i16 = 0x0020;
const POLLRDHUP: i16 = 0x2000;
/// The size of the kernel's signal set, which `ppoll` wants even with no
/// set: 64 signals on every architecture oscall supports.
const SIGSET_SIZE: usize = 8;
/// `struct pollfd`.
#[repr(C)]
#[derive(Clone, Copy)]
pub(crate) struct PollFd {
fd: i32,
events: i16,
revents: i16,
}
impl PollFd {
pub(crate) fn new(fd: RawHandle, interest: Interest) -> Self {
let mut events = 0;
if interest.contains(Interest::READABLE) {
// The peer's shutdown is part of what a reader waits for.
events |= POLLIN | POLLRDHUP;
}
if interest.contains(Interest::WRITABLE) {
events |= POLLOUT;
}
Self {
fd,
events,
revents: 0,
}
}
pub(crate) fn raw(&self) -> RawHandle {
self.fd
}
/// The events asked for, as the kernel takes them (io_uring's poll).
pub(crate) fn events(&self) -> i16 {
self.events
}
/// An entry the kernel answered `revents` for.
pub(crate) fn answered(revents: i16) -> Self {
Self {
fd: -1,
events: 0,
revents,
}
}
pub(crate) fn interest(&self) -> Interest {
let mut interest = Interest::empty();
if self.events & POLLIN != 0 {
interest |= Interest::READABLE;
}
if self.events & POLLOUT != 0 {
interest |= Interest::WRITABLE;
}
interest
}
pub(crate) fn readiness(&self) -> Readiness {
let mut readiness = Readiness::empty();
for (bit, flag) in [
(POLLIN, Readiness::READABLE),
(POLLOUT, Readiness::WRITABLE),
(POLLERR, Readiness::ERROR),
(POLLHUP, Readiness::HANGUP),
(POLLRDHUP, Readiness::READ_CLOSED),
(POLLNVAL, Readiness::INVALID),
] {
if self.revents & bit != 0 {
readiness |= flag;
}
}
readiness
}
pub(crate) fn clear(&mut self) {
self.revents = 0;
}
}
pub(crate) fn poll(fds: &mut [PollFd], timeout: Option<Duration>) -> Result<usize> {
// A relative timeout, on CLOCK_MONOTONIC; seconds beyond what the kernel
// counts saturate to its "never". The kernel writes the time left back.
let mut timeout = timeout.map(Timespec::from_duration);
let timeout = timeout
.as_mut()
.map_or(core::ptr::null_mut(), core::ptr::from_mut);
let (ptr, len) = (fds.as_mut_ptr(), fds.len());
// SAFETY: the kernel reads and writes `len` entries of the slice, and
// one `__kernel_timespec` if the pointer is not null; there is no
// signal mask.
#[cfg(target_pointer_width = "32")]
let ready = unsafe { syscall!(PPOLL_TIME64, ptr, len, timeout, 0, SIGSET_SIZE) };
// SAFETY: as above; `timespec` has that layout on 64-bit architectures.
#[cfg(target_pointer_width = "64")]
let ready = unsafe { syscall!(PPOLL, ptr, len, timeout, 0, SIGSET_SIZE) };
ready
}
// ---------------------------------------------------------------------------
// The poller: epoll, an eventfd to wake it, a timerfd for its timers
// ---------------------------------------------------------------------------
#[cfg(feature = "alloc")]
pub(crate) use poller::{Poller, RawEvent};
#[cfg(feature = "alloc")]
mod poller {
use core::sync::atomic::{AtomicBool, Ordering};
use core::time::Duration;
use super::SIGSET_SIZE;
use crate::event::lock::Lock;
use crate::event::timers::{Op, Timers};
use crate::event::{Interest, ModeKind, Readiness};
use crate::sys::time::Timespec;
use crate::sys::{RawHandle, close, errno, syscall};
use crate::time::Clock;
use crate::{AsHandle, Result};
// include/uapi/linux/eventpoll.h
const EPOLL_CTL_ADD: u32 = 1;
const EPOLL_CTL_DEL: u32 = 2;
const EPOLL_CTL_MOD: u32 = 3;
const EPOLLIN: u32 = 0x0001;
const EPOLLOUT: u32 = 0x0004;
const EPOLLERR: u32 = 0x0008;
const EPOLLHUP: u32 = 0x0010;
const EPOLLRDHUP: u32 = 0x2000;
const EPOLLONESHOT: u32 = 1 << 30;
const EPOLLET: u32 = 1 << 31;
/// `EPOLL_CLOEXEC`, `EFD_CLOEXEC` and `TFD_CLOEXEC` are `O_CLOEXEC`,
/// `EFD_NONBLOCK` and `TFD_NONBLOCK` are `O_NONBLOCK`: the same values
/// on every supported architecture.
const O_CLOEXEC: u32 = 0o2000000;
const O_NONBLOCK: u32 = 0o4000;
// include/uapi/linux/time.h, include/uapi/linux/timerfd.h
const CLOCK_MONOTONIC: u32 = 1;
const TFD_TIMER_ABSTIME: u32 = 1;
/// The `data` of the registrations of the poller's own descriptors,
/// the eventfd and the timerfd: no token is `usize::MAX`. Which of the
/// two an event is about does not matter: both are looked at.
const INTERNAL: u64 = u64::MAX;
/// In the `events` of an event made here, for a timer that expired:
/// the kernel never reports this bit (`EPOLLET`, which is only ever
/// given to it). The other bits are then the count of expirations.
const TIMER: u32 = 1 << 31;
/// `struct epoll_event`, which is packed on x86_64 alone (so that the
/// 32-bit and the 64-bit layouts are the same there).
#[cfg_attr(target_arch = "x86_64", repr(C, packed))]
#[cfg_attr(not(target_arch = "x86_64"), repr(C))]
#[derive(Clone, Copy)]
pub(crate) struct RawEvent {
events: u32,
data: u64,
}
// 12 bytes where a 64-bit integer is aligned on 4 (x86) or the structure
// is packed (x86_64), 16 elsewhere.
const _: () = {
let size = if cfg!(any(target_arch = "x86_64", target_arch = "x86")) {
12
} else {
16
};
assert!(size_of::<RawEvent>() == size);
};
impl RawEvent {
pub(crate) const EMPTY: Self = Self { events: 0, data: 0 };
/// The event of a wake-up.
const WAKE: Self = Self {
events: 0,
data: INTERNAL,
};
/// The event of a timer that expired `count` times.
fn timer(token: usize, count: u64) -> Self {
Self {
events: TIMER | count.min((TIMER - 1).into()) as u32,
data: token as u64,
}
}
pub(crate) fn token(&self) -> usize {
self.data as usize
}
/// In what the kernel reports: an event of the poller's own
/// descriptors. In what a wait returns: a wake-up.
pub(crate) fn is_wake(&self) -> bool {
self.data == INTERNAL
}
pub(crate) fn is_timer(&self) -> bool {
self.events & TIMER != 0
}
pub(crate) fn expirations(&self) -> u64 {
(self.events & !TIMER).into()
}
pub(crate) fn readiness(&self) -> Readiness {
let events = self.events;
let mut readiness = Readiness::empty();
if events & TIMER != 0 {
return readiness;
}
for (bit, flag) in [
(EPOLLIN, Readiness::READABLE),
(EPOLLOUT, Readiness::WRITABLE),
(EPOLLERR, Readiness::ERROR),
(EPOLLHUP, Readiness::HANGUP),
(EPOLLRDHUP, Readiness::READ_CLOSED),
] {
if events & bit != 0 {
readiness |= flag;
}
}
readiness
}
}
/// `struct __kernel_itimerspec`.
#[repr(C)]
struct ITimerSpec {
interval: Timespec,
value: Timespec,
}
/// The timers, and the descriptor that fires for the earliest of them.
struct TimerState {
timers: Timers,
/// A `timerfd`, created for the first timer and registered
/// edge-triggered. It is never read: arming it again is what makes
/// it unreadable, and each expiry of what it was last armed for is
/// an edge, which one wait collects.
fd: Option<RawHandle>,
}
pub(crate) struct Poller {
epoll: RawHandle,
/// Registered edge-triggered and never read: each write is an edge,
/// which one wait collects.
wake: RawHandle,
/// A wake-up was asked for and no wait has reported it yet.
woken: AtomicBool,
timers: Lock<TimerState>,
}
/// The monotonic clock, in nanoseconds.
fn now() -> Result<u64> {
let now = crate::sys::time::clock(Clock::Monotonic)?;
Ok(u64::try_from(now.as_nanos()).unwrap_or(u64::MAX))
}
impl Poller {
pub(crate) fn new() -> Result<Self> {
// SAFETY: creates a descriptor.
let epoll = unsafe { syscall!(EPOLL_CREATE1, O_CLOEXEC) }? as RawHandle;
// SAFETY: creates a descriptor.
let wake = match unsafe { syscall!(EVENTFD2, 0, O_CLOEXEC | O_NONBLOCK) } {
Ok(wake) => wake as RawHandle,
Err(err) => {
// SAFETY: `epoll` was just opened and is not used again.
unsafe { close(epoll) };
return Err(err);
}
};
// From here the descriptors are closed by `drop`.
let poller = Self {
epoll,
wake,
woken: AtomicBool::new(false),
timers: Lock::new(TimerState {
timers: Timers::new(),
fd: None,
}),
};
poller.ctl(EPOLL_CTL_ADD, wake, EPOLLIN | EPOLLET, INTERNAL)?;
Ok(poller)
}
fn ctl(&self, op: u32, fd: RawHandle, events: u32, data: u64) -> Result<()> {
let mut event = RawEvent { events, data };
// SAFETY: the kernel reads one `epoll_event` (`EPOLL_CTL_DEL`
// ignores it).
unsafe { syscall!(EPOLL_CTL, self.epoll, op, fd, &raw mut event) }?;
Ok(())
}
pub(crate) fn register(
&self,
fd: RawHandle,
token: usize,
interest: Interest,
mode: ModeKind,
) -> Result<()> {
self.ctl(EPOLL_CTL_ADD, fd, events(interest, mode), token as u64)
}
pub(crate) fn modify(
&self,
fd: RawHandle,
token: usize,
interest: Interest,
mode: ModeKind,
) -> Result<()> {
self.ctl(EPOLL_CTL_MOD, fd, events(interest, mode), token as u64)
}
pub(crate) fn deregister(&self, fd: RawHandle) -> Result<()> {
self.ctl(EPOLL_CTL_DEL, fd, 0, 0)
}
/// The eventfd of the subscription, edge-triggered: an event for
/// each signal that arrives, since each is a write.
pub(crate) fn register_signals(
&self,
signals: &crate::sys::process::signal::Signals,
token: usize,
) -> Result<()> {
let fd = signals.handle().as_raw();
self.ctl(EPOLL_CTL_ADD, fd, EPOLLIN | EPOLLET, token as u64)
}
pub(crate) fn deregister_signals(
&self,
signals: &crate::sys::process::signal::Signals,
) -> Result<()> {
self.deregister(signals.handle().as_raw())
}
/// The pidfd of the child, which is readable once the child has
/// exited, and stays so when it has been waited for: one-shot.
pub(crate) fn register_child(
&self,
child: &crate::sys::process::Child,
_collected: bool,
token: usize,
) -> Result<()> {
let fd = child.handle().as_handle().as_raw();
self.ctl(EPOLL_CTL_ADD, fd, EPOLLIN | EPOLLONESHOT, token as u64)
}
pub(crate) fn deregister_child(&self, child: &crate::sys::process::Child) -> Result<()> {
self.deregister(child.handle().as_handle().as_raw())
}
/// Arms the timerfd for `deadline`, on the monotonic clock, or
/// disarms it. A deadline that has passed fires it at once.
fn arm(&self, timer: &mut Option<RawHandle>, deadline: Option<u64>) -> Result<()> {
let fd = match (*timer, deadline) {
(Some(fd), _) => fd,
(None, None) => return Ok(()),
(None, Some(_)) => {
// SAFETY: creates a descriptor.
let fd = unsafe {
syscall!(TIMERFD_CREATE, CLOCK_MONOTONIC, O_CLOEXEC | O_NONBLOCK)
}? as RawHandle;
if let Err(error) = self.ctl(EPOLL_CTL_ADD, fd, EPOLLIN | EPOLLET, INTERNAL) {
// SAFETY: `fd` was just opened and is not used
// again.
unsafe { close(fd) };
return Err(error);
}
*timer = Some(fd);
fd
}
};
// A value of zero disarms: the origin of the clock is a deadline
// like another, one nanosecond late.
let value = deadline.map_or(Duration::ZERO, |deadline| {
Duration::from_nanos(deadline.max(1))
});
let spec = ITimerSpec {
interval: Timespec::from_duration(Duration::ZERO),
value: Timespec::from_duration(value),
};
// SAFETY: the kernel reads one `__kernel_itimerspec`, and writes
// nothing: there is no old value to return.
#[cfg(target_pointer_width = "32")]
unsafe { syscall!(TIMERFD_SETTIME64, fd, TFD_TIMER_ABSTIME, &raw const spec, 0) }?;
// SAFETY: as above; `itimerspec` has that layout on 64-bit
// architectures.
#[cfg(target_pointer_width = "64")]
unsafe { syscall!(TIMERFD_SETTIME, fd, TFD_TIMER_ABSTIME, &raw const spec, 0) }?;
Ok(())
}
pub(crate) fn timer(&self, token: usize, op: Op) -> Result<()> {
let mut state = self.timers.lock();
let now = now()?;
let state = &mut *state;
let (timers, fd) = (&mut state.timers, &mut state.fd);
timers.apply(token, op, now, |deadline| self.arm(fd, deadline))
}
/// Writes the events of the timers that are due at the start of
/// `events`, returns their count, and arms the timerfd for what
/// comes next: always, since the edge that brought the caller here
/// is spent, and the next one is the next expiry of the timerfd.
/// What is due and does not fit is the next deadline, which has
/// passed: the timerfd fires at once.
fn expire(&self, events: &mut [RawEvent]) -> Result<usize> {
let mut state = self.timers.lock();
if state.fd.is_none() {
return Ok(0);
}
let now = now()?;
let count = state
.timers
.expire(now, events.len(), |index, token, count| {
events[index] = RawEvent::timer(token, count);
});
let next = state.timers.next();
self.arm(&mut state.fd, next).map(|()| count)
}
pub(crate) fn wait(
&self,
events: &mut [RawEvent],
timeout: Option<Duration>,
) -> Result<usize> {
// On the monotonic clock, for when the wait has to be made
// again: one that only looks, or has no end, needs none.
let deadline = match timeout {
Some(timeout) if !timeout.is_zero() => {
Some(crate::sys::time::clock(Clock::Monotonic)?.saturating_add(timeout))
}
_ => None,
};
let mut left = timeout;
let max = i32::try_from(events.len()).unwrap_or(i32::MAX);
loop {
// Milliseconds, rounded up so that the wait never ends
// early; -1 for no timeout, which is also what a timeout
// beyond what an `int` counts (24 days) becomes: shortened,
// it would be reported as passed when it has not.
// (`epoll_pwait2` counts in nanoseconds, but needs Linux
// 5.11.)
let milliseconds = left.map_or(-1, |left| {
i32::try_from(left.as_nanos().div_ceil(1_000_000)).unwrap_or(-1)
});
// SAFETY: the kernel writes at most `max` events to the
// slice; there is no signal mask.
let count = unsafe {
syscall!(
EPOLL_PWAIT,
self.epoll,
events.as_mut_ptr(),
max,
milliseconds,
0,
SIGSET_SIZE
)
}?;
if !events[..count].iter().any(RawEvent::is_wake) {
// Nothing but what the kernel reports as it is.
return Ok(count);
}
// The poller's own descriptors spoke: their events go, and
// what they announce takes their place. There is room for
// one event at least.
let mut kept = 0;
for index in 0..count {
let event = events[index];
if !event.is_wake() {
events[kept] = event;
kept += 1;
}
}
if self.woken.swap(false, Ordering::AcqRel) {
events[kept] = RawEvent::WAKE;
kept += 1;
}
match self.expire(&mut events[kept..]) {
Ok(expired) => kept += expired,
// What was collected is not lost to an error.
Err(_) if kept > 0 => {}
Err(error) => return Err(error),
}
if kept > 0 {
return Ok(kept);
}
// Nothing to report after all: a wake-up another wait has
// reported, a timer that was removed or moved. Wait for
// what is left.
match (timeout, deadline) {
(None, _) => {}
(Some(_), Some(deadline)) => {
let now = crate::sys::time::clock(Clock::Monotonic)?;
if now >= deadline {
return Ok(0);
}
left = Some(deadline - now);
}
(Some(_), None) => return Ok(0),
}
}
}
pub(crate) fn wake(&self) -> Result<()> {
if self.woken.swap(true, Ordering::AcqRel) {
// A wake-up is on its way to a wait already.
return Ok(());
}
let one = 1u64;
// SAFETY: the kernel reads the eight bytes of `one`.
match unsafe { syscall!(WRITE, self.wake, &raw const one, 8) } {
Ok(_) => Ok(()),
// The counter is full, and the descriptor readable.
Err(err) if err.raw_os_error() == errno::EAGAIN => Ok(()),
Err(err) => {
self.woken.store(false, Ordering::Release);
Err(err)
}
}
}
}
impl Drop for Poller {
fn drop(&mut self) {
let timer = self.timers.lock().fd;
// SAFETY: the descriptors are open, owned and not used again.
unsafe {
if let Some(timer) = timer {
close(timer);
}
close(self.wake);
close(self.epoll);
}
}
}
fn events(interest: Interest, mode: ModeKind) -> u32 {
let mut events = 0;
if interest.contains(Interest::READABLE) {
// The peer's shutdown is part of what a reader waits for.
events |= EPOLLIN | EPOLLRDHUP;
}
if interest.contains(Interest::WRITABLE) {
events |= EPOLLOUT;
}
events
| match mode {
ModeKind::Level => 0,
ModeKind::OneShot => EPOLLONESHOT,
ModeKind::Edge => EPOLLET,
}
}
}