lio 0.4.1

A platform-independent async I/O library with native support for io_uring (Linux), IOCP (Windows), and kqueue (macOS)
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
use super::{
  super::{Interest, ReadinessPoll},
  NOTIFY_KEY,
};

use std::cell::RefCell;
use std::marker::PhantomData;
use std::time::Duration;
use std::{
  collections::HashSet,
  os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd},
};
use std::{io, ptr};

/// Special identifier for EVFILT_USER notification events
const NOTIFY_IDENT: usize = NOTIFY_KEY as usize;

/// Wrapper around a kqueue file descriptor
///
/// This type is intentionally `!Send` to ensure it's only used from a single thread.
/// Interior mutability is provided via `RefCell` for tracking registered fds/timers.
pub struct OsPoller {
  kq_fd: OwnedFd,
  /// Track registered fds to match epoll's strict add/modify semantics
  registered_fds: RefCell<HashSet<RawFd>>,
  /// Track registered timer keys separately (timers don't have fds)
  registered_timers: RefCell<HashSet<u64>>,
  notify: notify::Notify,
  /// Marker to make this type `!Send`
  _not_send: PhantomData<*const ()>,
}

impl OsPoller {
  /// Create a new kqueue instance
  pub fn new() -> io::Result<Self> {
    // Create kqueue
    // SAFETY: syscall!(kqueue()) returns a valid file descriptor or error.
    // If successful, we immediately take ownership of it via OwnedFd.
    let kqueue_fd = unsafe { OwnedFd::from_raw_fd(syscall!(kqueue())?) };
    syscall!(fcntl(kqueue_fd.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC))?;

    let kqueue = Self {
      kq_fd: kqueue_fd,
      registered_fds: RefCell::new(HashSet::new()),
      registered_timers: RefCell::new(HashSet::new()),
      notify: notify::Notify::new()?,
      _not_send: PhantomData,
    };

    kqueue.notify.register(&kqueue)?;

    Ok(kqueue)
  }

  pub(crate) fn submit_changes(
    &self,
    changelist: &[<Self as ReadinessPoll>::NativeEvent],
  ) -> io::Result<()> {
    let changes = changelist;
    let nchanges = changes.len();

    let mut eventlist: Vec<<Self as ReadinessPoll>::NativeEvent> =
      Vec::with_capacity(nchanges);

    let spare = eventlist.spare_capacity_mut();
    let nevents = spare.len();

    syscall!(kevent(
      self.kq_fd.as_raw_fd(),
      changes.as_ptr(),
      nchanges as libc::c_int,
      spare.as_mut_ptr().cast(),
      nevents as libc::c_int,
      ptr::null(),
    ))?;

    for ev in &eventlist {
      if (ev.flags & libc::EV_ERROR) != 0 {
        let err_code = ev.data as i32;
        if err_code != 0 && err_code != libc::ENOENT && err_code != libc::EPIPE
        {
          return Err(io::Error::from_raw_os_error(err_code));
        }
      }
    }

    Ok(())
  }

  /// Add or modify multiple interests in a single syscall (batched)
  ///
  /// This is more efficient than calling add_interest/modify_interest twice
  /// when both readable and writable interests are needed.
  fn change_interests_batched(
    &self,
    fd: RawFd,
    key: usize,
    interest: Interest,
  ) -> io::Result<()> {
    // For kqueue timers, fd contains duration in milliseconds
    if interest.is_timer() {
      let duration_ms = fd;

      let kev = libc::kevent {
        ident: key as libc::uintptr_t,
        filter: libc::EVFILT_TIMER,
        flags: libc::EV_ADD | libc::EV_ENABLE | libc::EV_ONESHOT,
        fflags: 0,
        data: duration_ms as isize,
        udata: key as *mut libc::c_void,
      };

      syscall!(kevent(
        self.kq_fd.as_raw_fd(),
        &kev as *const libc::kevent,
        1,
        ptr::null_mut(),
        0,
        ptr::null(),
      ))?;

      return Ok(());
    }

    // SAFETY: libc::kevent is a C struct that is safe to zero-initialize.
    // All fields are primitive integers/pointers where zero is a valid bit pattern.
    let mut changes: [libc::kevent; 2] = unsafe { std::mem::zeroed() };
    let mut n = 0;

    if interest.is_readable() {
      changes[n] = libc::kevent {
        ident: fd as libc::uintptr_t,
        filter: libc::EVFILT_READ,
        flags: libc::EV_ADD | libc::EV_ENABLE | libc::EV_ONESHOT,
        fflags: 0,
        data: 0,
        udata: key as *mut libc::c_void,
      };
      n += 1;
    }

    if interest.is_writable() {
      assert!(n < 2, "Must have space for WRITE event");
      changes[n] = libc::kevent {
        ident: fd as libc::uintptr_t,
        filter: libc::EVFILT_WRITE,
        flags: libc::EV_ADD | libc::EV_ENABLE | libc::EV_ONESHOT,
        fflags: 0,
        data: 0,
        udata: key as *mut libc::c_void,
      };
      n += 1;
    }

    assert!(n <= 2, "n must be 0, 1, or 2, got {}", n);

    if n > 0 {
      let ret = syscall!(kevent(
        self.kq_fd.as_raw_fd(),
        changes.as_ptr(),
        n as i32,
        ptr::null_mut(),
        0,
        ptr::null(),
      ))?;

      assert_eq!(
        ret, 0,
        "kevent with no output events should return 0, got {}",
        ret
      );
    }

    Ok(())
  }

  /// Delete interest for a file descriptor
  fn delete_interest(&self, fd: RawFd, filter: i16) -> io::Result<()> {
    let kev = libc::kevent {
      ident: fd as libc::uintptr_t,
      filter,
      flags: libc::EV_DELETE,
      fflags: 0,
      data: 0,
      udata: ptr::null_mut(),
    };

    let result = syscall!(kevent(
      self.kq_fd.as_raw_fd(),
      &kev as *const libc::kevent,
      1,
      std::ptr::null_mut(),
      0,
      std::ptr::null(),
    ));

    match result {
      Err(err) if !utils::is_not_found_error(&err) => Err(err),
      _ => Ok(()),
    }
  }
}

impl ReadinessPoll for OsPoller {
  type NativeEvent = libc::kevent;

  fn add(&self, fd: RawFd, key: u64, interest: Interest) -> io::Result<()> {
    // For timers, track by key instead of fd
    if interest.is_timer() {
      if !self.registered_timers.borrow_mut().insert(key) {
        return Err(io::Error::from_raw_os_error(libc::EEXIST));
      }

      match self.change_interests_batched(fd, key as usize, interest) {
        Ok(()) => Ok(()),
        Err(e) => {
          self.registered_timers.borrow_mut().remove(&key);
          Err(e)
        }
      }
    } else {
      // Check if fd is already registered (match epoll's EEXIST behavior)
      if !self.registered_fds.borrow_mut().insert(fd) {
        // Value already existed
        return Err(io::Error::from_raw_os_error(libc::EEXIST));
      }

      // Optimization: batch both read and write into a single syscall
      match self.change_interests_batched(fd, key as usize, interest) {
        Ok(()) => {
          // Postcondition: fd must still be in registered_fds
          assert!(
            self.registered_fds.borrow().contains(&fd),
            "fd should be in registered_fds after successful add"
          );
          Ok(())
        }
        Err(e) => {
          // Rollback: remove from tracking if syscall failed
          let removed = self.registered_fds.borrow_mut().remove(&fd);
          assert!(
            removed,
            "fd should have been in registered_fds for rollback"
          );
          Err(e)
        }
      }
    }
  }

  fn modify(&self, fd: RawFd, key: u64, interest: Interest) -> io::Result<()> {
    if interest.is_timer() {
      if !self.registered_timers.borrow().contains(&key) {
        return Err(io::Error::from_raw_os_error(libc::ENOENT));
      }
      self.change_interests_batched(fd, key as usize, interest)
    } else {
      // Check if fd is registered (match epoll's ENOENT behavior)
      if !self.registered_fds.borrow().contains(&fd) {
        return Err(io::Error::from_raw_os_error(libc::ENOENT));
      }

      let result = self.change_interests_batched(fd, key as usize, interest);

      // Postcondition: fd should still be registered regardless of success/failure
      assert!(
        self.registered_fds.borrow().contains(&fd),
        "fd should still be in registered_fds after modify"
      );

      result
    }
  }

  fn delete(&self, fd: RawFd) -> io::Result<()> {
    // Check if fd is registered, fail with ENOENT if not
    if !self.registered_fds.borrow_mut().remove(&fd) {
      return Err(io::Error::from_raw_os_error(libc::ENOENT));
    }

    // Postcondition: fd should no longer be in registered_fds
    assert!(
      !self.registered_fds.borrow().contains(&fd),
      "fd should not be in registered_fds after remove"
    );

    // Delete both read and write interests
    let read_result = self.delete_interest(fd, libc::EVFILT_READ);
    let write_result = self.delete_interest(fd, libc::EVFILT_WRITE);

    // If either deletion succeeded, we're good
    // If both failed, check if either had a non-ENOENT error
    match (read_result, write_result) {
      (Ok(()), _) | (_, Ok(())) => Ok(()),
      (Err(read_err), Err(write_err)) => {
        // Both failed - check if either is a real error (not ENOENT)
        if !utils::is_not_found_error(&read_err) {
          Err(read_err)
        } else if !utils::is_not_found_error(&write_err) {
          Err(write_err)
        } else {
          // Both were ENOENT - this shouldn't happen since fd was in registered_fds
          // but if it does, treat it as success (filters were already deleted)
          Ok(())
        }
      }
    }
  }

  fn delete_timer(&self, key: u64) -> io::Result<()> {
    // Check if timer key is registered, fail with ENOENT if not
    if !self.registered_timers.borrow_mut().remove(&key) {
      return Err(io::Error::from_raw_os_error(libc::ENOENT));
    }

    // Delete EVFILT_TIMER using the key as ident
    let kev = libc::kevent {
      ident: key as libc::uintptr_t,
      filter: libc::EVFILT_TIMER,
      flags: libc::EV_DELETE,
      fflags: 0,
      data: 0,
      udata: ptr::null_mut(),
    };

    let result = syscall!(kevent(
      self.kq_fd.as_raw_fd(),
      &kev as *const libc::kevent,
      1,
      std::ptr::null_mut(),
      0,
      std::ptr::null(),
    ));

    match result {
      Err(err) if !utils::is_not_found_error(&err) => Err(err),
      _ => Ok(()),
    }
  }

  fn wait(
    &self,
    events: &mut [Self::NativeEvent],
    timeout: Option<Duration>,
  ) -> io::Result<usize> {
    // Convert timeout and create pointer from storage reference
    let timeout_storage = utils::timeout_to_timespec(timeout);
    let timeout_ptr = timeout_storage
      .as_ref()
      .map_or(std::ptr::null(), |ts| ts as *const libc::timespec);

    let ret = syscall!(kevent(
      self.kq_fd.as_raw_fd(),
      std::ptr::null(),
      0,
      events.as_mut_ptr(),
      events.len() as i32,
      timeout_ptr,
    ))?;

    let n = ret as usize;
    assert!(
      n <= events.len(),
      "kevent returned more events ({}) than buffer size ({})",
      n,
      events.len()
    );

    Ok(n)
  }

  fn notify(&self) -> io::Result<()> {
    // Use kqueue-native EVFILT_USER notification
    let kev = libc::kevent {
      ident: NOTIFY_IDENT as libc::uintptr_t,
      filter: libc::EVFILT_USER,
      flags: 0,
      fflags: libc::NOTE_TRIGGER, // Trigger the user event
      data: 0,
      udata: NOTIFY_IDENT as *mut libc::c_void,
    };

    syscall!(kevent(
      self.kq_fd.as_raw_fd(),
      &kev as *const libc::kevent,
      1,
      ptr::null_mut(),
      0,
      ptr::null(),
    ))?;

    Ok(())
  }

  fn event_key(event: &Self::NativeEvent) -> u64 {
    event.udata as u64
  }

  fn event_interest(event: &Self::NativeEvent) -> Interest {
    // kqueue returns one event per filter, so only one will be set
    match event.filter {
      libc::EVFILT_READ => Interest::READ,
      libc::EVFILT_WRITE => Interest::WRITE,
      libc::EVFILT_TIMER => Interest::TIMER,
      _ => Interest::READ, // Fallback
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  crate::generate_tests!(OsPoller::new().unwrap());
}

mod utils {
  use std::io;
  use std::time::Duration;

  /// Convert Duration to libc::timespec
  ///
  /// Shared between kqueue and epoll implementations
  pub fn duration_to_timespec(duration: Duration) -> libc::timespec {
    libc::timespec {
      tv_sec: duration.as_secs() as libc::time_t,
      tv_nsec: duration.subsec_nanos() as libc::c_long,
    }
  }

  /// Convert Option<Duration> to timespec storage
  ///
  /// Returns the timespec value that must be kept alive for the duration of the syscall.
  /// The caller should create a pointer from a reference to this storage.
  pub fn timeout_to_timespec(
    timeout: Option<Duration>,
  ) -> Option<libc::timespec> {
    timeout.map(duration_to_timespec)
  }

  /// Check if an error is "not found" (ENOENT)
  ///
  /// Used when deleting non-existent fd interests - should not error
  pub fn is_not_found_error(err: &io::Error) -> bool {
    err.raw_os_error() == Some(libc::ENOENT)
  }

  #[cfg(test)]
  mod tests {
    use super::*;

    #[test]
    fn test_duration_to_timespec() {
      let dur = Duration::from_millis(1500);
      let ts = duration_to_timespec(dur);
      assert_eq!(ts.tv_sec, 1);
      assert_eq!(ts.tv_nsec, 500_000_000);
    }

    #[test]
    fn test_timeout_to_timespec_some() {
      let dur = Duration::from_millis(2500);
      let timeout = Some(dur);
      let storage = timeout_to_timespec(timeout);

      // Verify storage contains the correct value
      assert!(storage.is_some());
      let ts = storage.unwrap();
      assert_eq!(ts.tv_sec, 2);
      assert_eq!(ts.tv_nsec, 500_000_000);

      // Verify that creating a pointer from storage is valid
      // This mimics what the caller should do
      let ptr = &ts as *const libc::timespec;
      assert!(!ptr.is_null());

      // Verify the pointer points to valid data
      unsafe {
        assert_eq!((*ptr).tv_sec, 2);
        assert_eq!((*ptr).tv_nsec, 500_000_000);
      }
    }

    #[test]
    fn test_timeout_to_timespec_none() {
      let storage = timeout_to_timespec(None);
      assert!(storage.is_none());
    }

    #[test]
    fn test_is_not_found_error() {
      let err = io::Error::from_raw_os_error(libc::ENOENT);
      assert!(is_not_found_error(&err));

      let err = io::Error::from_raw_os_error(libc::EINVAL);
      assert!(!is_not_found_error(&err));
    }
  }
}

#[cfg(any(
  target_os = "freebsd",
  target_os = "dragonfly",
  target_vendor = "apple",
))]
#[allow(dead_code)]
mod notify {
  use super::*;
  use crate::backends::pollingv2::os::NOTIFY_KEY;
  use std::io;

  /// A notification pipe.
  ///
  /// This implementation uses `EVFILT_USER` to avoid allocating a pipe.
  #[derive(Debug)]
  pub(super) struct Notify;

  impl Notify {
    /// Creates a new notification pipe.
    pub(super) fn new() -> io::Result<Self> {
      Ok(Self)
    }

    /// Registers this notification pipe in the `Poller`.
    pub(super) fn register(&self, poller: &OsPoller) -> io::Result<()> {
      // Register an EVFILT_USER event.
      // IMPORTANT: ident must match what notify() uses to trigger the event
      poller.submit_changes(&[libc::kevent {
        ident: NOTIFY_IDENT as libc::uintptr_t,
        filter: libc::EVFILT_USER,
        flags: (libc::EV_ADD | libc::EV_RECEIPT | libc::EV_CLEAR) as _,
        fflags: 0,
        data: 0,
        udata: NOTIFY_KEY as *mut _,
      }])
    }

    /// Reregister this notification pipe in the `Poller`.
    pub(super) fn reregister(&self, _poller: &OsPoller) -> io::Result<()> {
      // We don't need to do anything, it's already registered as EV_CLEAR.
      Ok(())
    }

    /// Notifies the `Poller`.
    pub(super) fn notify(&self, poller: &OsPoller) -> io::Result<()> {
      // Trigger the EVFILT_USER event.
      poller.submit_changes(&[libc::kevent {
        ident: 0,
        filter: libc::EVFILT_USER as _,
        flags: (libc::EV_ADD | libc::EV_RECEIPT) as _,
        fflags: libc::NOTE_TRIGGER,
        data: 0,
        udata: NOTIFY_KEY as *mut _,
      }])?;

      Ok(())
    }

    /// Deregisters this notification pipe from the `Poller`.
    pub(super) fn deregister(&self, poller: &OsPoller) -> io::Result<()> {
      // Deregister the EVFILT_USER event.
      poller.submit_changes(&[libc::kevent {
        ident: 0,
        filter: libc::EVFILT_USER as _,
        flags: (libc::EV_DELETE | libc::EV_RECEIPT) as _,
        fflags: 0,
        data: 0,
        udata: NOTIFY_KEY as *mut _,
      }])
    }
  }
}

#[cfg(not(any(
  target_os = "freebsd",
  target_os = "dragonfly",
  target_vendor = "apple",
)))]
mod notify {
  use super::Poller;
  use crate::{Event, NOTIFY_KEY, PollMode};
  use std::io::{self, prelude::*};
  #[cfg(feature = "tracing")]
  use std::os::unix::io::BorrowedFd;
  use std::os::unix::{
    io::{AsFd, AsRawFd},
    net::UnixStream,
  };

  /// A notification pipe.
  ///
  /// This implementation uses a pipe to send notifications.
  #[derive(Debug)]
  pub(super) struct Notify {
    /// The read end of the pipe.
    read_stream: UnixStream,

    /// The write end of the pipe.
    write_stream: UnixStream,
  }

  impl Notify {
    /// Creates a new notification pipe.
    pub(super) fn new() -> io::Result<Self> {
      let (read_stream, write_stream) = UnixStream::pair()?;
      read_stream.set_nonblocking(true)?;
      write_stream.set_nonblocking(true)?;

      Ok(Self { read_stream, write_stream })
    }

    /// Registers this notification pipe in the `Poller`.
    pub(super) fn register(&self, poller: &Poller) -> io::Result<()> {
      // Register the read end of this pipe.
      unsafe {
        poller.add(
          self.read_stream.as_raw_fd(),
          Event::readable(NOTIFY_KEY),
          PollMode::Oneshot,
        )
      }
    }

    /// Reregister this notification pipe in the `Poller`.
    pub(super) fn reregister(&self, poller: &Poller) -> io::Result<()> {
      // Clear out the notification.
      while (&self.read_stream).read(&mut [0; 64]).is_ok() {}

      // Reregister the read end of this pipe.
      poller.modify(
        self.read_stream.as_fd(),
        Event::readable(NOTIFY_KEY),
        PollMode::Oneshot,
      )
    }

    /// Notifies the `Poller`.
    #[allow(clippy::unused_io_amount)]
    pub(super) fn notify(&self, _poller: &Poller) -> io::Result<()> {
      // Write to the write end of the pipe
      (&self.write_stream).write(&[1])?;

      Ok(())
    }

    /// Deregisters this notification pipe from the `Poller`.
    pub(super) fn deregister(&self, poller: &Poller) -> io::Result<()> {
      // Deregister the read end of the pipe.
      poller.delete(self.read_stream.as_fd())
    }

    /// Whether this raw file descriptor is associated with this pipe.
    #[cfg(feature = "tracing")]
    pub(super) fn has_fd(&self, fd: BorrowedFd<'_>) -> bool {
      self.read_stream.as_raw_fd() == fd.as_raw_fd()
    }
  }
}