oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
//! `event` on macOS: `poll`.
//!
//! Constants and layouts are those of `<sys/poll.h>`.

use core::ffi::{c_int, c_uint};
use core::time::Duration;

use crate::Result;
use crate::event::{Interest, Readiness};
use crate::sys::{RawHandle, cvt};

const POLLIN: i16 = 0x0001;
const POLLOUT: i16 = 0x0004;
const POLLERR: i16 = 0x0008;
const POLLHUP: i16 = 0x0010;
const POLLNVAL: i16 = 0x0020;

/// `struct pollfd`.
#[repr(C)]
#[derive(Clone, Copy)]
pub(crate) struct PollFd {
    fd: c_int,
    events: i16,
    revents: i16,
}

unsafe extern "C" {
    #[link_name = "poll"]
    fn c_poll(fds: *mut PollFd, count: c_uint, timeout: c_int) -> c_int;
}

impl PollFd {
    pub(crate) fn new(fd: RawHandle, interest: Interest) -> Self {
        let mut events = 0;
        if interest.contains(Interest::READABLE) {
            events |= POLLIN;
        }
        if interest.contains(Interest::WRITABLE) {
            events |= POLLOUT;
        }
        Self {
            fd,
            events,
            revents: 0,
        }
    }

    pub(crate) fn raw(&self) -> RawHandle {
        self.fd
    }

    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),
            (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> {
    // 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.
    let timeout = timeout.map_or(-1, |timeout| {
        c_int::try_from(timeout.as_nanos().div_ceil(1_000_000)).unwrap_or(-1)
    });
    // More entries than descriptors can exist is an error the system reports.
    let count = c_uint::try_from(fds.len()).unwrap_or(c_uint::MAX);
    // SAFETY: the system reads and writes `count` entries of the slice.
    let ready = cvt(unsafe { c_poll(fds.as_mut_ptr(), count, timeout) })?;
    Ok(ready as usize)
}

// ---------------------------------------------------------------------------
// The poller: kqueue
// ---------------------------------------------------------------------------

#[cfg(feature = "alloc")]
pub(crate) use poller::{Poller, RawEvent};

/// Constants and layouts are those of `<sys/event.h>`.
#[cfg(feature = "alloc")]
mod poller {
    use alloc::collections::BTreeMap;
    use core::ffi::{c_int, c_long};
    use core::sync::atomic::{AtomicUsize, Ordering};
    use core::time::Duration;

    use crate::event::lock::Lock;
    use crate::event::timers::{Op, Timers};
    use crate::event::{Interest, ModeKind, Readiness};
    use crate::sys::{RawHandle, close, cvt, errno};
    use crate::time::Clock;
    use crate::{Error, ErrorKind, Result};

    const EVFILT_READ: i16 = -1;
    const EVFILT_WRITE: i16 = -2;
    const EVFILT_PROC: i16 = -5;
    const EVFILT_TIMER: i16 = -7;
    const EVFILT_USER: i16 = -10;

    const EV_ADD: u16 = 0x0001;
    const EV_DELETE: u16 = 0x0002;
    const EV_ONESHOT: u16 = 0x0010;
    const EV_CLEAR: u16 = 0x0020;
    const EV_RECEIPT: u16 = 0x0040;
    const EV_DISPATCH: u16 = 0x0080;
    const EV_ERROR: u16 = 0x4000;
    const EV_EOF: u16 = 0x8000;

    const NOTE_TRIGGER: u32 = 0x0100_0000;
    /// For `EVFILT_PROC`: the process exits.
    const NOTE_EXIT: u32 = 0x8000_0000;
    /// For `EVFILT_TIMER`: `data` is in nanoseconds; and the timer is not
    /// to be delayed to save power, beyond what the system does to all.
    const NOTE_NSECONDS: u32 = 0x0000_0004;
    const NOTE_CRITICAL: u32 = 0x0000_0020;

    /// The identifier of the poller's two own filters: the user event of
    /// `wake` (no process is 0, and the user events made for children have
    /// their process identifier) and the timer.
    const OWN: usize = 0;
    /// The longest the timer is armed for at once, in nanoseconds: a day.
    /// It is armed again when it fires with nothing due.
    const MAX_TIMER: u64 = 86_400 * 1_000_000_000;

    const F_SETFD: c_int = 2;
    const FD_CLOEXEC: c_int = 1;

    /// The longest timeout given to the kernel, as for a sleep: 136 years.
    /// A longer one is no timeout.
    const MAX_WAIT_SECS: u64 = u32::MAX as u64;

    /// The `udata` of the user event `wake` triggers.
    const WAKE: usize = usize::MAX;
    /// The most changes one registration makes: both filters deleted, both
    /// added.
    const MAX_CHANGES: usize = 4;

    /// `struct kevent`. `udata` is a pointer to the system, and a token
    /// here.
    #[repr(C)]
    #[derive(Clone, Copy)]
    pub(crate) struct RawEvent {
        ident: usize,
        filter: i16,
        flags: u16,
        fflags: u32,
        data: isize,
        udata: usize,
    }

    const _: () = assert!(size_of::<RawEvent>() == 32);

    /// `struct timespec`.
    #[repr(C)]
    struct Timespec {
        sec: i64,
        nsec: c_long,
    }

    unsafe extern "C" {
        fn kqueue() -> c_int;
        fn kevent(
            kq: c_int,
            changes: *const RawEvent,
            change_count: c_int,
            events: *mut RawEvent,
            event_count: c_int,
            timeout: *const Timespec,
        ) -> c_int;
        fn fcntl(fd: c_int, cmd: c_int, ...) -> c_int;
    }

    impl RawEvent {
        pub(crate) const EMPTY: Self = Self {
            ident: 0,
            filter: 0,
            flags: 0,
            fflags: 0,
            data: 0,
            udata: 0,
        };

        fn change(fd: RawHandle, filter: i16, flags: u16, token: usize) -> Self {
            Self {
                ident: fd as usize,
                filter,
                flags: flags | EV_RECEIPT,
                udata: token,
                ..Self::EMPTY
            }
        }

        pub(crate) fn token(&self) -> usize {
            self.udata
        }

        pub(crate) fn is_wake(&self) -> bool {
            self.filter == EVFILT_USER && self.ident == OWN
        }

        /// The event of a timer that expired `count` times, in the shape of
        /// the system's own for a timer. (Those are never returned: the one
        /// timer the system has for the poller is the poller's own.)
        fn timer(token: usize, count: u64) -> Self {
            Self {
                ident: token,
                filter: EVFILT_TIMER,
                data: isize::try_from(count).unwrap_or(isize::MAX),
                udata: token,
                ..Self::EMPTY
            }
        }

        pub(crate) fn is_timer(&self) -> bool {
            self.filter == EVFILT_TIMER
        }

        pub(crate) fn expirations(&self) -> u64 {
            self.data as u64
        }

        pub(crate) fn readiness(&self) -> Readiness {
            let eof = self.flags & EV_EOF != 0;
            let mut readiness = match self.filter {
                // A child that exited: `fflags` has `NOTE_EXIT`, which is
                // not a socket's error. Or (a user event) one that had
                // exited before it was registered.
                EVFILT_PROC | EVFILT_USER => return Readiness::READABLE,
                // The end of the stream is something to read.
                EVFILT_READ if eof => Readiness::READABLE | Readiness::READ_CLOSED,
                EVFILT_READ => Readiness::READABLE,
                // Nothing more can be sent: the connection is gone.
                EVFILT_WRITE if eof => Readiness::WRITABLE | Readiness::HANGUP,
                EVFILT_WRITE => Readiness::WRITABLE,
                _ => Readiness::empty(),
            };
            // With the end of the stream, `fflags` is the socket's error.
            if self.flags & EV_ERROR != 0 || (eof && self.fflags != 0) {
                readiness |= Readiness::ERROR;
            }
            readiness
        }
    }

    pub(crate) struct Poller {
        kq: RawHandle,
        /// The descriptors that are registered: kqueue itself does not say
        /// whether a filter existed before a change, and adds what it is
        /// asked to modify.
        ///
        /// The value is `Some` for a one-shot registration of both
        /// directions, and tells whether it is armed. kqueue has a filter
        /// for each direction, which it disarms separately: this is what
        /// makes the two one registration, that reports once.
        ///
        /// The lock is held across the changes made to the queue, so that
        /// the table and the queue agree.
        registered: Lock<BTreeMap<RawHandle, Option<bool>>>,
        /// How many one-shot registrations of both directions there are,
        /// to leave the lock alone in `wait` when there is none.
        tracked: AtomicUsize,
        /// The process identifiers of the children that are registered.
        /// The filter of a child is deleted by the system when it has
        /// fired, and the child is registered still.
        children: Lock<BTreeMap<c_int, ()>>,
        /// The timers. The lock is held while the system's timer is armed
        /// for the earliest of them.
        timers: Lock<Timers>,
    }

    /// The flags of a filter for `mode`.
    fn mode_flags(mode: ModeKind) -> u16 {
        match mode {
            ModeKind::Level => 0,
            // `EV_DISPATCH` disables the filter when it has fired, where
            // `EV_ONESHOT` would delete it.
            ModeKind::OneShot => EV_DISPATCH,
            ModeKind::Edge => EV_CLEAR,
        }
    }

    fn monotonic() -> Result<Duration> {
        crate::sys::time::clock(Clock::Monotonic)
    }

    impl Poller {
        pub(crate) fn new() -> Result<Self> {
            // SAFETY: creates a descriptor.
            let kq = cvt(unsafe { kqueue() })?;
            // From here the descriptor is closed by `drop`.
            let poller = Self {
                kq,
                registered: Lock::new(BTreeMap::new()),
                tracked: AtomicUsize::new(0),
                children: Lock::new(BTreeMap::new()),
                timers: Lock::new(Timers::new()),
            };
            // SAFETY: `kq` is open; the third argument is the `int` the
            // command takes.
            cvt(unsafe { fcntl(kq, F_SETFD, FD_CLOEXEC) })?;
            // The event `wake` triggers, which clears itself when reported.
            let user = RawEvent {
                ident: OWN,
                filter: EVFILT_USER,
                flags: EV_ADD | EV_CLEAR | EV_RECEIPT,
                udata: WAKE,
                ..RawEvent::EMPTY
            };
            if let Some(code) = poller.apply(&[user])?.into_iter().find(|&code| code != 0) {
                return Err(Error::from_raw_os_error(code));
            }
            Ok(poller)
        }

        /// Makes `changes`, each of which has `EV_RECEIPT`, and returns the
        /// error number of each (0 for success).
        fn apply(&self, changes: &[RawEvent]) -> Result<[i32; MAX_CHANGES]> {
            let mut receipts = [RawEvent::EMPTY; MAX_CHANGES];
            let count = changes.len().min(MAX_CHANGES) as c_int;
            let zero = Timespec { sec: 0, nsec: 0 };
            // SAFETY: the system reads `count` changes and writes a receipt
            // for each, for which there is room and no more: no event is
            // taken from the queue.
            let written = cvt(unsafe {
                kevent(
                    self.kq,
                    changes.as_ptr(),
                    count,
                    receipts.as_mut_ptr(),
                    count,
                    &raw const zero,
                )
            })?;
            if written != count {
                return Err(ErrorKind::Other.into());
            }
            let mut codes = [0; MAX_CHANGES];
            for (code, receipt) in codes.iter_mut().zip(&receipts[..written as usize]) {
                if receipt.flags & EV_ERROR != 0 {
                    *code = receipt.data as i32;
                }
            }
            Ok(codes)
        }

        /// What the table holds for a registration.
        fn entry(interest: Interest, mode: ModeKind) -> Option<bool> {
            let both = Interest::READABLE | Interest::WRITABLE;
            (matches!(mode, ModeKind::OneShot) && interest.contains(both)).then_some(true)
        }

        /// Counts the registrations `wait` has to look at.
        fn count(&self, table: &BTreeMap<RawHandle, Option<bool>>) {
            let tracked = table.values().filter(|entry| entry.is_some()).count();
            self.tracked.store(tracked, Ordering::Release);
        }

        /// Deletes both filters of a descriptor, whether or not they are
        /// there.
        fn delete(&self, fd: RawHandle) {
            let _ = self.apply(&[
                RawEvent::change(fd, EVFILT_READ, EV_DELETE, 0),
                RawEvent::change(fd, EVFILT_WRITE, EV_DELETE, 0),
            ]);
        }

        /// Adds the filters of a registration, after deleting those the
        /// descriptor has if `replace`: a filter that exists would keep
        /// its mode, and its state if it was disabled.
        fn set(
            &self,
            fd: RawHandle,
            token: usize,
            interest: Interest,
            mode: ModeKind,
            replace: bool,
        ) -> Result<()> {
            let mut changes = [RawEvent::EMPTY; MAX_CHANGES];
            let mut count = 0;
            if replace {
                changes[0] = RawEvent::change(fd, EVFILT_READ, EV_DELETE, 0);
                changes[1] = RawEvent::change(fd, EVFILT_WRITE, EV_DELETE, 0);
                count = 2;
            }
            let deletions = count;
            for (direction, filter) in [
                (Interest::READABLE, EVFILT_READ),
                (Interest::WRITABLE, EVFILT_WRITE),
            ] {
                if interest.contains(direction) {
                    let flags = EV_ADD | mode_flags(mode);
                    changes[count] = RawEvent::change(fd, filter, flags, token);
                    count += 1;
                }
            }
            match self.apply(&changes[..count]) {
                Ok(codes) => codes[..count]
                    .iter()
                    .enumerate()
                    // A filter that was not there to delete is no failure.
                    .find(|&(index, &code)| {
                        code != 0 && !(index < deletions && code == errno::ENOENT)
                    })
                    .map_or(Ok(()), |(_, &code)| Err(Error::from_raw_os_error(code))),
                Err(err) => Err(err),
            }
        }

        pub(crate) fn register(
            &self,
            fd: RawHandle,
            token: usize,
            interest: Interest,
            mode: ModeKind,
        ) -> Result<()> {
            let mut table = self.registered.lock();
            if table.contains_key(&fd) {
                return Err(ErrorKind::AlreadyExists.into());
            }
            // In the table first: an event may come before `set` returns.
            table.insert(fd, Self::entry(interest, mode));
            self.count(&table);
            let result = self.set(fd, token, interest, mode, false);
            if result.is_err() {
                // Leave nothing behind: one filter may have been added.
                self.delete(fd);
                table.remove(&fd);
                self.count(&table);
            }
            result
        }

        pub(crate) fn modify(
            &self,
            fd: RawHandle,
            token: usize,
            interest: Interest,
            mode: ModeKind,
        ) -> Result<()> {
            let mut table = self.registered.lock();
            let Some(entry) = table.get_mut(&fd) else {
                return Err(ErrorKind::NotFound.into());
            };
            *entry = Self::entry(interest, mode);
            self.count(&table);
            let result = self.set(fd, token, interest, mode, true);
            if result.is_err() {
                // Still registered, as it is elsewhere when a modification
                // fails, but watching nothing: one filter of the two may
                // have been added.
                self.delete(fd);
            }
            result
        }

        pub(crate) fn deregister(&self, fd: RawHandle) -> Result<()> {
            let mut table = self.registered.lock();
            if table.remove(&fd).is_none() {
                return Err(ErrorKind::NotFound.into());
            }
            self.count(&table);
            // A filter that is not there is no failure: the registration
            // had one direction, or the descriptor was closed and the
            // system dropped its filters then.
            self.delete(fd);
            Ok(())
        }

        /// The handle of the subscription, edge-triggered: an event each
        /// time its handler writes to the pipe.
        pub(crate) fn register_signals(
            &self,
            signals: &crate::sys::process::signal::Signals,
            token: usize,
        ) -> Result<()> {
            let fd = signals.handle().as_raw();
            self.register(fd, token, Interest::READABLE, ModeKind::Edge)
        }

        pub(crate) fn deregister_signals(
            &self,
            signals: &crate::sys::process::signal::Signals,
        ) -> Result<()> {
            self.deregister(signals.handle().as_raw())
        }

        /// Deletes the filters a child may have, whether or not they are
        /// there.
        fn delete_child(&self, pid: c_int) {
            let _ = self.apply(&[
                RawEvent::change(pid, EVFILT_PROC, EV_DELETE, 0),
                RawEvent::change(pid, EVFILT_USER, EV_DELETE, 0),
            ]);
        }

        pub(crate) fn register_child(
            &self,
            child: &crate::sys::process::Child,
            collected: bool,
            token: usize,
        ) -> Result<()> {
            let pid = child.id() as c_int;
            let mut children = self.children.lock();
            if children.contains_key(&pid) {
                return Err(ErrorKind::AlreadyExists.into());
            }
            children.insert(pid, ());
            let result = self.watch_child(pid, collected || child.is_gone(), token);
            if result.is_err() {
                self.delete_child(pid);
                children.remove(&pid);
            }
            result
        }

        /// Adds the filter that fires when process `pid` exits, or, if it
        /// has `exited` already, the event that says so.
        fn watch_child(&self, pid: c_int, exited: bool, token: usize) -> Result<()> {
            if !exited {
                let mut exit = RawEvent::change(pid, EVFILT_PROC, EV_ADD | EV_ONESHOT, token);
                exit.fflags = NOTE_EXIT;
                match self.apply(&[exit])?[0] {
                    0 => return Ok(()),
                    // The system only watches a process that runs: this
                    // one, which is a child that was not waited for, has
                    // exited.
                    errno::ESRCH => {}
                    code => return Err(Error::from_raw_os_error(code)),
                }
            }
            // A user event of its own, triggered at once and deleted when
            // it is reported: no process is 0, the event of `wake`.
            let add = RawEvent::change(pid, EVFILT_USER, EV_ADD | EV_ONESHOT, token);
            let mut trigger = RawEvent::change(pid, EVFILT_USER, 0, token);
            trigger.fflags = NOTE_TRIGGER;
            match self
                .apply(&[add, trigger])?
                .into_iter()
                .find(|&code| code != 0)
            {
                None => Ok(()),
                Some(code) => Err(Error::from_raw_os_error(code)),
            }
        }

        pub(crate) fn deregister_child(&self, child: &crate::sys::process::Child) -> Result<()> {
            let pid = child.id() as c_int;
            let mut children = self.children.lock();
            if children.remove(&pid).is_none() {
                return Err(ErrorKind::NotFound.into());
            }
            self.delete_child(pid);
            Ok(())
        }

        /// Arms the system's timer for `deadline`, on the monotonic clock
        /// which reads `now`, or deletes it. It fires once; a deadline that
        /// has passed fires it at once.
        fn arm(&self, deadline: Option<u64>, now: u64) -> Result<()> {
            let Some(deadline) = deadline else {
                // Not there if it has fired, or never was armed.
                let _ = self.apply(&[RawEvent::change(0, EVFILT_TIMER, EV_DELETE, 0)]);
                return Ok(());
            };
            // Relative to now, on the clock the queue is kept on
            // (`mach_absolute_time`): adding to a timer that exists arms it
            // anew.
            let mut timer = RawEvent::change(0, EVFILT_TIMER, EV_ADD | EV_ONESHOT, WAKE);
            timer.fflags = NOTE_NSECONDS | NOTE_CRITICAL;
            timer.data = deadline.saturating_sub(now).clamp(1, MAX_TIMER) as isize;
            match self.apply(&[timer])?[0] {
                0 => Ok(()),
                code => Err(Error::from_raw_os_error(code)),
            }
        }

        fn now() -> Result<u64> {
            Ok(u64::try_from(monotonic()?.as_nanos()).unwrap_or(u64::MAX))
        }

        pub(crate) fn timer(&self, token: usize, op: Op) -> Result<()> {
            let mut timers = self.timers.lock();
            let now = Self::now()?;
            timers.apply(token, op, now, |deadline| self.arm(deadline, now))
        }

        /// Writes the events of the timers that are due at the start of
        /// `events`, returns their count, and arms the system's timer for
        /// what comes next: it has fired, and is no more. What is due and
        /// does not fit is the next deadline, which has passed: the timer
        /// fires at once.
        fn expire(&self, events: &mut [RawEvent]) -> Result<usize> {
            let mut timers = self.timers.lock();
            let now = Self::now()?;
            let count = timers.expire(now, events.len(), |index, token, count| {
                events[index] = RawEvent::timer(token, count);
            });
            self.arm(timers.next(), now).map(|()| count)
        }

        pub(crate) fn wait(
            &self,
            events: &mut [RawEvent],
            timeout: Option<Duration>,
        ) -> Result<usize> {
            let max = c_int::try_from(events.len()).unwrap_or(c_int::MAX);
            // On the clock `Clock::Monotonic` reads, for when the wait has
            // to be made again.
            let deadline = match timeout {
                Some(timeout) => Some(monotonic()?.saturating_add(timeout)),
                None => None,
            };
            let mut left = timeout;
            loop {
                // The kernel adds the timeout to its clock, and refuses
                // one that overflows it (`EINVAL`): beyond `MAX_WAIT_SECS`
                // there is no timeout at all.
                let timespec = left
                    .filter(|left| left.as_secs() <= MAX_WAIT_SECS)
                    .map(|left| Timespec {
                        sec: left.as_secs() as i64,
                        nsec: left.subsec_nanos().into(),
                    });
                let timespec = timespec
                    .as_ref()
                    .map_or(core::ptr::null(), |t| t as *const _);
                // SAFETY: the system writes at most `max` events to the
                // slice, and reads one `timespec` if the pointer is not
                // null.
                let count = cvt(unsafe {
                    kevent(
                        self.kq,
                        core::ptr::null(),
                        0,
                        events.as_mut_ptr(),
                        max,
                        timespec,
                    )
                })? as usize;
                // The system's timer is the poller's own: its event goes,
                // and those of the timers that are due take its place.
                let fired = events[..count].iter().any(RawEvent::is_timer);
                if count == 0 || (!fired && self.tracked.load(Ordering::Acquire) == 0) {
                    return Ok(count);
                }
                // A one-shot registration of both directions reports once:
                // the event of the other filter, if it comes before the
                // registration is armed again, is not one.
                let mut kept = 0;
                {
                    let mut table =
                        (self.tracked.load(Ordering::Acquire) != 0).then(|| self.registered.lock());
                    for index in 0..count {
                        let event = events[index];
                        if event.is_timer() {
                            continue;
                        }
                        if matches!(event.filter, EVFILT_READ | EVFILT_WRITE)
                            && let Some(table) = table.as_mut()
                            && let Some(Some(armed)) = table.get_mut(&(event.ident as RawHandle))
                        {
                            if !*armed {
                                continue;
                            }
                            *armed = false;
                        }
                        events[kept] = event;
                        kept += 1;
                    }
                }
                if fired {
                    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: wait for what is left.
                if let Some(deadline) = deadline {
                    let now = monotonic()?;
                    if now >= deadline {
                        return Ok(0);
                    }
                    left = Some(deadline - now);
                }
            }
        }

        pub(crate) fn wake(&self) -> Result<()> {
            let trigger = RawEvent {
                ident: OWN,
                filter: EVFILT_USER,
                fflags: NOTE_TRIGGER,
                udata: WAKE,
                ..RawEvent::EMPTY
            };
            let zero = Timespec { sec: 0, nsec: 0 };
            // SAFETY: the system reads one change and writes no event.
            cvt(unsafe {
                kevent(
                    self.kq,
                    &raw const trigger,
                    1,
                    core::ptr::null_mut(),
                    0,
                    &raw const zero,
                )
            })?;
            Ok(())
        }
    }

    impl Drop for Poller {
        fn drop(&mut self) {
            // SAFETY: the descriptor is open, owned and not used again.
            unsafe { close(self.kq) };
        }
    }
}