Debian Codegraph @

src/poll.rs

raw symbols SCIP
1 //! Bindings to poll (VxWorks, Fuchsia, other Unix systems).
2
3 use std::collections::HashMap;
4 use std::io;
5 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
6 use std::sync::{Condvar, Mutex};
7 use std::time::Instant;
8
9 #[cfg(not(target_os = "hermit"))]
10 use rustix::fd::{AsFd, AsRawFd, BorrowedFd};
11 #[cfg(target_os = "hermit")]
12 use std::os::hermit::io::{AsFd, AsRawFd, BorrowedFd};
13
14 use syscall::{poll, PollFd, PollFlags};
15
16 // std::os::unix doesn't exist on Fuchsia
17 type RawFd = std::os::raw::c_int;
18
19 use crate::{Event, PollMode};
20
21 /// Interface to poll.
22 #[derive(Debug)]
23 pub struct Poller {
24 /// File descriptors to poll.
25 fds: Mutex<Fds>,
26 /// Notification pipe for waking up the poller.
27 ///
28 /// On all platforms except ESP IDF, the `pipe` syscall is used.
29 /// On ESP IDF, the `eventfd` syscall is used instead.
30 notify: notify::Notify,
31 /// The number of operations (`add`, `modify` or `delete`) that are currently waiting on the
32 /// mutex to become free. When this is nonzero, `wait` must be suspended until it reaches zero
33 /// again.
34 waiting_operations: AtomicUsize,
35 /// Whether `wait` has been notified by the user.
36 notified: AtomicBool,
37 /// The condition variable that gets notified when `waiting_operations` reaches zero or
38 /// `notified` becomes true.
39 ///
40 /// This is used with the `fds` mutex.
41 operations_complete: Condvar,
42 }
43
44 /// The file descriptors to poll in a `Poller`.
45 #[derive(Debug)]
46 struct Fds {
47 /// The list of `pollfds` taken by poll.
48 ///
49 /// The first file descriptor is always present and is used to notify the poller. It is also
50 /// stored in `notify_read`.
51 poll_fds: Vec<PollFd<'static>>,
52 /// The map of each file descriptor to data associated with it. This does not include the file
53 /// descriptors `notify_read` or `notify_write`.
54 fd_data: HashMap<RawFd, FdData>,
55 }
56
57 /// Data associated with a file descriptor in a poller.
58 #[derive(Debug)]
59 struct FdData {
60 /// The index into `poll_fds` this file descriptor is.
61 poll_fds_index: usize,
62 /// The key of the `Event` associated with this file descriptor.
63 key: usize,
64 /// Whether to remove this file descriptor from the poller on the next call to `wait`.
65 remove: bool,
66 }
67
68 impl Poller {
69 /// Creates a new poller.
70 pub fn new() -> io::Result<Poller> {
71 let notify = notify::Notify::new()?;
72
73 #[cfg(feature = "tracing")]
74 tracing::trace!(?notify, "new");
75
76 Ok(Self {
77 fds: Mutex::new(Fds {
78 poll_fds: vec![PollFd::from_borrowed_fd(
79 // SAFETY: `notify.fd()` will remain valid until we drop `self`.
80 unsafe { BorrowedFd::borrow_raw(notify.fd().as_raw_fd()) },
81 notify.poll_flags(),
82 )],
83 fd_data: HashMap::new(),
84 }),
85 notify,
86 waiting_operations: AtomicUsize::new(0),
87 operations_complete: Condvar::new(),
88 notified: AtomicBool::new(false),
89 })
90 }
91
92 /// Whether this poller supports level-triggered events.
93 pub fn supports_level(&self) -> bool {
94 true
95 }
96
97 /// Whether the poller supports edge-triggered events.
98 pub fn supports_edge(&self) -> bool {
99 false
100 }
101
102 /// Adds a new file descriptor.
103 pub fn add(&self, fd: RawFd, ev: Event, mode: PollMode) -> io::Result<()> {
104 if self.notify.has_fd(fd) {
105 return Err(io::Error::from(io::ErrorKind::InvalidInput));
106 }
107
108 #[cfg(feature = "tracing")]
109 let span = tracing::trace_span!(
110 "add",
111 notify_read = ?self.notify.fd().as_raw_fd(),
112 ?fd,
113 ?ev,
114 );
115 #[cfg(feature = "tracing")]
116 let _enter = span.enter();
117
118 self.modify_fds(|fds| {
119 if fds.fd_data.contains_key(&fd) {
120 return Err(io::Error::from(io::ErrorKind::AlreadyExists));
121 }
122
123 let poll_fds_index = fds.poll_fds.len();
124 fds.fd_data.insert(
125 fd,
126 FdData {
127 poll_fds_index,
128 key: ev.key,
129 remove: cvt_mode_as_remove(mode)?,
130 },
131 );
132
133 fds.poll_fds.push(PollFd::from_borrowed_fd(
134 // SAFETY: Until we have I/O safety, assume that `fd` is valid forever.
135 unsafe { BorrowedFd::borrow_raw(fd) },
136 poll_events(ev),
137 ));
138
139 Ok(())
140 })
141 }
142
143 /// Modifies an existing file descriptor.
144 pub fn modify(&self, fd: BorrowedFd<'_>, ev: Event, mode: PollMode) -> io::Result<()> {
145 if self.notify.has_fd(fd.as_raw_fd()) {
146 return Err(io::Error::from(io::ErrorKind::InvalidInput));
147 }
148
149 #[cfg(feature = "tracing")]
150 let span = tracing::trace_span!(
151 "modify",
152 notify_read = ?self.notify.fd().as_raw_fd(),
153 ?fd,
154 ?ev,
155 );
156 #[cfg(feature = "tracing")]
157 let _enter = span.enter();
158
159 self.modify_fds(|fds| {
160 let data = fds
161 .fd_data
162 .get_mut(&fd.as_raw_fd())
163 .ok_or(io::ErrorKind::NotFound)?;
164 data.key = ev.key;
165 let poll_fds_index = data.poll_fds_index;
166
167 // SAFETY: This is essentially transmuting a `PollFd<'a>` to a `PollFd<'static>`, which
168 // only works if it's removed in time with `delete()`.
169 fds.poll_fds[poll_fds_index] = PollFd::from_borrowed_fd(
170 unsafe { BorrowedFd::borrow_raw(fd.as_raw_fd()) },
171 poll_events(ev),
172 );
173 data.remove = cvt_mode_as_remove(mode)?;
174
175 Ok(())
176 })
177 }
178
179 /// Deletes a file descriptor.
180 pub fn delete(&self, fd: BorrowedFd<'_>) -> io::Result<()> {
181 if self.notify.has_fd(fd.as_raw_fd()) {
182 return Err(io::Error::from(io::ErrorKind::InvalidInput));
183 }
184
185 #[cfg(feature = "tracing")]
186 let span = tracing::trace_span!(
187 "delete",
188 notify_read = ?self.notify.fd().as_raw_fd(),
189 ?fd,
190 );
191 #[cfg(feature = "tracing")]
192 let _enter = span.enter();
193
194 self.modify_fds(|fds| {
195 let data = fds
196 .fd_data
197 .remove(&fd.as_raw_fd())
198 .ok_or(io::ErrorKind::NotFound)?;
199 fds.poll_fds.swap_remove(data.poll_fds_index);
200 if let Some(swapped_pollfd) = fds.poll_fds.get(data.poll_fds_index) {
201 fds.fd_data
202 .get_mut(&swapped_pollfd.as_fd().as_raw_fd())
203 .unwrap()
204 .poll_fds_index = data.poll_fds_index;
205 }
206
207 Ok(())
208 })
209 }
210
211 /// Waits for I/O events with an optional deadline.
212 pub fn wait_deadline(&self, events: &mut Events, deadline: Option<Instant>) -> io::Result<()> {
213 #[cfg(feature = "tracing")]
214 let span = tracing::trace_span!(
215 "wait",
216 notify_read = ?self.notify.fd().as_raw_fd(),
217 ?deadline,
218 );
219 #[cfg(feature = "tracing")]
220 let _enter = span.enter();
221
222 let mut fds = self.fds.lock().unwrap();
223
224 loop {
225 // Complete all current operations.
226 loop {
227 if self.notified.swap(false, Ordering::SeqCst) {
228 // `notify` will have sent a notification in case we were polling. We weren't,
229 // so remove it.
230 return self.notify.pop_notification();
231 } else if self.waiting_operations.load(Ordering::SeqCst) == 0 {
232 break;
233 }
234
235 fds = self.operations_complete.wait(fds).unwrap();
236 }
237
238 let timeout =
239 deadline.map(|deadline| deadline.saturating_duration_since(Instant::now()));
240
241 // Perform the poll.
242 let num_events = poll(&mut fds.poll_fds, timeout)?;
243 let notified = !fds.poll_fds[0].revents().is_empty();
244 let num_fd_events = if notified { num_events - 1 } else { num_events };
245 #[cfg(feature = "tracing")]
246 tracing::trace!(?num_events, ?notified, ?num_fd_events, "new events",);
247
248 // Read all notifications.
249 if notified {
250 self.notify.pop_all_notifications()?;
251 }
252
253 // If the only event that occurred during polling was notification and it wasn't to
254 // exit, another thread is trying to perform an operation on the fds. Continue the
255 // loop.
256 if !self.notified.swap(false, Ordering::SeqCst) && num_fd_events == 0 && notified {
257 continue;
258 }
259
260 // Store the events if there were any.
261 if num_fd_events > 0 {
262 let fds = &mut *fds;
263
264 events.inner.reserve(num_fd_events);
265 for fd_data in fds.fd_data.values_mut() {
266 let poll_fd = &mut fds.poll_fds[fd_data.poll_fds_index];
267 if !poll_fd.revents().is_empty() {
268 // Store event
269 let revents = poll_fd.revents();
270 events.inner.push(Event {
271 key: fd_data.key,
272 readable: revents.intersects(read_events()),
273 writable: revents.intersects(write_events()),
274 extra: EventExtra { flags: revents },
275 });
276 // Remove interest if necessary
277 if fd_data.remove {
278 *poll_fd = PollFd::from_borrowed_fd(
279 unsafe { BorrowedFd::borrow_raw(poll_fd.as_fd().as_raw_fd()) },
280 PollFlags::empty(),
281 );
282 }
283
284 if events.inner.len() == num_fd_events {
285 break;
286 }
287 }
288 }
289 }
290
291 break;
292 }
293
294 Ok(())
295 }
296
297 /// Sends a notification to wake up the current or next `wait()` call.
298 pub fn notify(&self) -> io::Result<()> {
299 #[cfg(feature = "tracing")]
300 let span = tracing::trace_span!(
301 "notify",
302 notify_read = ?self.notify.fd().as_raw_fd(),
303 );
304 #[cfg(feature = "tracing")]
305 let _enter = span.enter();
306
307 if !self.notified.swap(true, Ordering::SeqCst) {
308 self.notify.notify()?;
309 self.operations_complete.notify_one();
310 }
311
312 Ok(())
313 }
314
315 /// Perform a modification on `fds`, interrupting the current caller of `wait` if it's running.
316 fn modify_fds(&self, f: impl FnOnce(&mut Fds) -> io::Result<()>) -> io::Result<()> {
317 self.waiting_operations.fetch_add(1, Ordering::SeqCst);
318
319 // Wake up the current caller of `wait` if there is one.
320 let sent_notification = self.notify.notify().is_ok();
321
322 let mut fds = self.fds.lock().unwrap();
323
324 // If there was no caller of `wait` our notification was not removed from the pipe.
325 if sent_notification {
326 let _ = self.notify.pop_notification();
327 }
328
329 let res = f(&mut fds);
330
331 if self.waiting_operations.fetch_sub(1, Ordering::SeqCst) == 1 {
332 self.operations_complete.notify_one();
333 }
334
335 res
336 }
337 }
338
339 /// Get the input poll events for the given event.
340 fn poll_events(ev: Event) -> PollFlags {
341 (if ev.readable {
342 PollFlags::IN | PollFlags::PRI
343 } else {
344 PollFlags::empty()
345 }) | (if ev.writable {
346 PollFlags::OUT | PollFlags::WRBAND
347 } else {
348 PollFlags::empty()
349 })
350 }
351
352 /// Returned poll events for reading.
353 fn read_events() -> PollFlags {
354 PollFlags::IN | PollFlags::PRI | PollFlags::HUP | PollFlags::ERR
355 }
356
357 /// Returned poll events for writing.
358 fn write_events() -> PollFlags {
359 PollFlags::OUT | PollFlags::WRBAND | PollFlags::HUP | PollFlags::ERR
360 }
361
362 /// A list of reported I/O events.
363 pub struct Events {
364 inner: Vec<Event>,
365 }
366
367 impl Events {
368 /// Creates an empty list.
369 pub fn with_capacity(cap: usize) -> Events {
370 Self {
371 inner: Vec::with_capacity(cap),
372 }
373 }
374
375 /// Iterates over I/O events.
376 pub fn iter(&self) -> impl Iterator<Item = Event> + '_ {
377 self.inner.iter().copied()
378 }
379
380 /// Clear the list.
381 pub fn clear(&mut self) {
382 self.inner.clear();
383 }
384
385 /// Get the capacity of the list.
386 pub fn capacity(&self) -> usize {
387 self.inner.capacity()
388 }
389 }
390
391 /// Extra information associated with an event.
392 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
393 pub struct EventExtra {
394 /// Flags associated with this event.
395 flags: PollFlags,
396 }
397
398 impl EventExtra {
399 /// Creates an empty set of extra information.
400 #[inline]
401 pub const fn empty() -> Self {
402 Self {
403 flags: PollFlags::empty(),
404 }
405 }
406
407 /// Set the interrupt flag.
408 #[inline]
409 pub fn set_hup(&mut self, value: bool) {
410 self.flags.set(PollFlags::HUP, value);
411 }
412
413 /// Set the priority flag.
414 #[inline]
415 pub fn set_pri(&mut self, value: bool) {
416 self.flags.set(PollFlags::PRI, value);
417 }
418
419 /// Is this an interrupt event?
420 #[inline]
421 pub fn is_hup(&self) -> bool {
422 self.flags.contains(PollFlags::HUP)
423 }
424
425 /// Is this a priority event?
426 #[inline]
427 pub fn is_pri(&self) -> bool {
428 self.flags.contains(PollFlags::PRI)
429 }
430
431 #[inline]
432 pub fn is_connect_failed(&self) -> Option<bool> {
433 Some(self.flags.contains(PollFlags::ERR) || self.flags.contains(PollFlags::HUP))
434 }
435
436 #[inline]
437 pub fn is_err(&self) -> Option<bool> {
438 Some(self.flags.contains(PollFlags::ERR))
439 }
440 }
441
442 fn cvt_mode_as_remove(mode: PollMode) -> io::Result<bool> {
443 match mode {
444 PollMode::Oneshot => Ok(true),
445 PollMode::Level => Ok(false),
446 _ => Err(crate::unsupported_error(
447 "edge-triggered I/O events are not supported in poll()",
448 )),
449 }
450 }
451
452 #[cfg(unix)]
453 mod syscall {
454 pub(super) use rustix::event::{PollFd, PollFlags};
455
456 pub(super) use rustix::event::Timespec;
457 #[cfg(target_os = "espidf")]
458 pub(super) use rustix::event::{eventfd, EventfdFlags};
459 #[cfg(target_os = "espidf")]
460 pub(super) use rustix::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd, RawFd};
461 #[cfg(target_os = "espidf")]
462 pub(super) use rustix::io::{read, write};
463 use std::io;
464 use std::time::Duration;
465
466 /// Safe wrapper around the `poll` system call.
467 pub(super) fn poll(fds: &mut [PollFd<'_>], timeout: Option<Duration>) -> io::Result<usize> {
468 // Timeout for `poll`. In case of overflow, use no timeout.
469 let timeout = match timeout {
470 Some(timeout) => Timespec::try_from(timeout).ok(),
471 None => None,
472 };
473
474 Ok(rustix::event::poll(fds, timeout.as_ref())?)
475 }
476 }
477
478 #[cfg(target_os = "hermit")]
479 mod syscall {
480 // TODO: Remove this shim once HermitOS is supported in Rustix.
481
482 use std::fmt;
483 use std::io;
484 use std::marker::PhantomData;
485 use std::ops::BitOr;
486 use std::time::Duration;
487
488 pub(super) use std::os::hermit::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd, RawFd};
489
490 /// Create an eventfd.
491 pub(super) fn eventfd(count: u64, _flags: EventfdFlags) -> io::Result<OwnedFd> {
492 let fd = unsafe { hermit_abi::eventfd(count, 0) };
493
494 if fd < 0 {
495 Err(io::Error::from_raw_os_error(unsafe {
496 hermit_abi::get_errno()
497 }))
498 } else {
499 Ok(unsafe { OwnedFd::from_raw_fd(fd) })
500 }
501 }
502
503 /// Read some bytes.
504 pub(super) fn read(fd: BorrowedFd<'_>, bytes: &mut [u8]) -> io::Result<usize> {
505 let count = unsafe { hermit_abi::read(fd.as_raw_fd(), bytes.as_mut_ptr(), bytes.len()) };
506
507 cvt(count)
508 }
509
510 /// Write some bytes.
511 pub(super) fn write(fd: BorrowedFd<'_>, bytes: &[u8]) -> io::Result<usize> {
512 let count = unsafe { hermit_abi::write(fd.as_raw_fd(), bytes.as_ptr(), bytes.len()) };
513
514 cvt(count)
515 }
516
517 /// Safe wrapper around the `poll` system call.
518 pub(super) fn poll(fds: &mut [PollFd<'_>], timeout: Option<Duration>) -> io::Result<usize> {
519 // Timeout in milliseconds for epoll. In case of overflow, use no timeout.
520 let mut timeout_ms = -1;
521 if let Some(t) = timeout {
522 if let Ok(ms) = i32::try_from(t.as_millis()) {
523 // Round up to a whole millisecond.
524 if Duration::from_millis(ms as u64) < t {
525 if let Some(ms) = ms.checked_add(1) {
526 timeout_ms = ms;
527 }
528 } else {
529 timeout_ms = ms;
530 }
531 }
532 }
533
534 let call = unsafe {
535 hermit_abi::poll(
536 fds.as_mut_ptr() as *mut hermit_abi::pollfd,
537 fds.len(),
538 timeout_ms,
539 )
540 };
541
542 cvt(call as isize)
543 }
544
545 /// Safe wrapper around `pollfd`.
546 #[repr(transparent)]
547 pub(super) struct PollFd<'a> {
548 inner: hermit_abi::pollfd,
549 _lt: PhantomData<BorrowedFd<'a>>,
550 }
551
552 impl<'a> PollFd<'a> {
553 pub(super) fn from_borrowed_fd(fd: BorrowedFd<'a>, inflags: PollFlags) -> Self {
554 Self {
555 inner: hermit_abi::pollfd {
556 fd: fd.as_raw_fd(),
557 events: inflags.0,
558 revents: 0,
559 },
560 _lt: PhantomData,
561 }
562 }
563
564 pub(super) fn revents(&self) -> PollFlags {
565 PollFlags(self.inner.revents)
566 }
567 }
568
569 impl AsFd for PollFd<'_> {
570 fn as_fd(&self) -> BorrowedFd<'_> {
571 unsafe { BorrowedFd::borrow_raw(self.inner.fd) }
572 }
573 }
574
575 impl fmt::Debug for PollFd<'_> {
576 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
577 f.debug_struct("PollFd")
578 .field("fd", &format_args!("0x{:x}", self.inner.fd))
579 .field("events", &PollFlags(self.inner.events))
580 .field("revents", &PollFlags(self.inner.revents))
581 .finish()
582 }
583 }
584
585 /// Wrapper around polling flags.
586 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
587 pub(super) struct PollFlags(i16);
588
589 impl PollFlags {
590 /// Empty set of flags.
591 pub(super) const fn empty() -> Self {
592 Self(0)
593 }
594
595 pub(super) const IN: PollFlags = PollFlags(hermit_abi::POLLIN);
596 pub(super) const OUT: PollFlags = PollFlags(hermit_abi::POLLOUT);
597 pub(super) const WRBAND: PollFlags = PollFlags(hermit_abi::POLLWRBAND);
598 pub(super) const ERR: PollFlags = PollFlags(hermit_abi::POLLERR);
599 pub(super) const HUP: PollFlags = PollFlags(hermit_abi::POLLHUP);
600 pub(super) const PRI: PollFlags = PollFlags(hermit_abi::POLLPRI);
601
602 /// Tell if this contains some flags.
603 pub(super) fn contains(self, flags: PollFlags) -> bool {
604 self.0 & flags.0 != 0
605 }
606
607 /// Set a flag.
608 pub(super) fn set(&mut self, flags: PollFlags, set: bool) {
609 if set {
610 self.0 |= flags.0;
611 } else {
612 self.0 &= !(flags.0);
613 }
614 }
615
616 /// Tell if this is empty.
617 pub(super) fn is_empty(self) -> bool {
618 self.0 == 0
619 }
620
621 /// Tell if this intersects with some flags.
622 pub(super) fn intersects(self, flags: PollFlags) -> bool {
623 self.contains(flags)
624 }
625 }
626
627 impl BitOr for PollFlags {
628 type Output = PollFlags;
629
630 fn bitor(self, rhs: Self) -> Self::Output {
631 Self(self.0 | rhs.0)
632 }
633 }
634
635 #[derive(Debug, Copy, Clone)]
636 pub(super) struct EventfdFlags;
637
638 impl EventfdFlags {
639 pub(super) fn empty() -> Self {
640 Self
641 }
642 }
643
644 /// Convert a number to an actual result.
645 #[inline]
646 fn cvt(len: isize) -> io::Result<usize> {
647 if len < 0 {
648 Err(io::Error::from_raw_os_error(unsafe {
649 hermit_abi::get_errno()
650 }))
651 } else {
652 Ok(len as usize)
653 }
654 }
655 }
656
657 #[cfg(not(any(target_os = "espidf", target_os = "hermit")))]
658 mod notify {
659 use std::io;
660
661 use rustix::event::PollFlags;
662 use rustix::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd, RawFd};
663 use rustix::fs::{fcntl_getfl, fcntl_setfl, OFlags};
664 use rustix::io::{fcntl_getfd, fcntl_setfd, read, write, FdFlags};
665 #[cfg(not(any(target_os = "haiku", target_os = "nto")))]
666 use rustix::pipe::pipe_with;
667 use rustix::pipe::{pipe, PipeFlags};
668
669 /// A notification pipe.
670 ///
671 /// This implementation uses a pipe to send notifications.
672 #[derive(Debug)]
673 pub(super) struct Notify {
674 /// The file descriptor of the read half of the notify pipe. This is also stored as the first
675 /// file descriptor in `fds.poll_fds`.
676 read_pipe: OwnedFd,
677 /// The file descriptor of the write half of the notify pipe.
678 ///
679 /// Data is written to this to wake up the current instance of `Poller::wait`, which can occur when the
680 /// user notifies it (in which case `Poller::notified` would have been set) or when an operation needs
681 /// to occur (in which case `Poller::waiting_operations` would have been incremented).
682 write_pipe: OwnedFd,
683 }
684
685 impl Notify {
686 /// Creates a new notification pipe.
687 pub(super) fn new() -> io::Result<Self> {
688 let fallback_pipe = |_| {
689 let (read_pipe, write_pipe) = pipe()?;
690 fcntl_setfd(&read_pipe, fcntl_getfd(&read_pipe)? | FdFlags::CLOEXEC)?;
691 fcntl_setfd(&write_pipe, fcntl_getfd(&write_pipe)? | FdFlags::CLOEXEC)?;
692 io::Result::Ok((read_pipe, write_pipe))
693 };
694
695 #[cfg(not(any(target_os = "haiku", target_os = "nto")))]
696 let (read_pipe, write_pipe) = pipe_with(PipeFlags::CLOEXEC).or_else(fallback_pipe)?;
697
698 #[cfg(any(target_os = "haiku", target_os = "nto"))]
699 let (read_pipe, write_pipe) = fallback_pipe(PipeFlags::CLOEXEC)?;
700
701 // Put the reading side into non-blocking mode.
702 fcntl_setfl(&read_pipe, fcntl_getfl(&read_pipe)? | OFlags::NONBLOCK)?;
703
704 Ok(Self {
705 read_pipe,
706 write_pipe,
707 })
708 }
709
710 /// Provides the file handle of the read half of the notify pipe that needs to be registered by the `Poller`.
711 pub(super) fn fd(&self) -> BorrowedFd<'_> {
712 self.read_pipe.as_fd()
713 }
714
715 /// Provides the poll flags to be used when registering the read half of the notify pipe with the `Poller`.
716 pub(super) fn poll_flags(&self) -> PollFlags {
717 PollFlags::RDNORM
718 }
719
720 /// Notifies the `Poller` instance via the write half of the notify pipe.
721 pub(super) fn notify(&self) -> Result<(), io::Error> {
722 write(&self.write_pipe, &[0; 1])?;
723
724 Ok(())
725 }
726
727 /// Pops a notification (if any) from the pipe.
728 pub(super) fn pop_notification(&self) -> Result<(), io::Error> {
729 // Pipes on Vita do not guarantee that after `write` call succeeds, the
730 // data becomes immediately available for reading on the other side of the pipe.
731 // To ensure that the notification is not lost, the read side of the pipe is temporarily
732 // switched to blocking for a single `read` call.
733 #[cfg(target_os = "vita")]
734 rustix::fs::fcntl_setfl(
735 &self.read_pipe,
736 rustix::fs::fcntl_getfl(&self.read_pipe)? & !rustix::fs::OFlags::NONBLOCK,
737 )?;
738
739 let result = read(&self.read_pipe, &mut [0; 1]);
740
741 #[cfg(target_os = "vita")]
742 rustix::fs::fcntl_setfl(
743 &self.read_pipe,
744 rustix::fs::fcntl_getfl(&self.read_pipe)? | rustix::fs::OFlags::NONBLOCK,
745 )?;
746
747 result?;
748
749 Ok(())
750 }
751
752 /// Pops all notifications from the pipe.
753 pub(super) fn pop_all_notifications(&self) -> Result<(), io::Error> {
754 while read(&self.read_pipe, &mut [0; 64]).is_ok() {}
755
756 Ok(())
757 }
758
759 /// Whether this raw file descriptor is associated with this notifier.
760 pub(super) fn has_fd(&self, fd: RawFd) -> bool {
761 self.read_pipe.as_raw_fd() == fd || self.write_pipe.as_raw_fd() == fd
762 }
763 }
764 }
765
766 #[cfg(any(target_os = "espidf", target_os = "hermit"))]
767 mod notify {
768 use std::io;
769 use std::mem;
770
771 use super::syscall::{
772 eventfd, read, write, AsFd, AsRawFd, BorrowedFd, EventfdFlags, OwnedFd, PollFlags, RawFd,
773 };
774
775 /// A notification pipe.
776 ///
777 /// This implementation uses the `eventfd` syscall to send notifications.
778 #[derive(Debug)]
779 pub(super) struct Notify {
780 /// The file descriptor of the eventfd object. This is also stored as the first
781 /// file descriptor in `fds.poll_fds`.
782 ///
783 /// Data is written to this to wake up the current instance of `Poller::wait`, which can occur when the
784 /// user notifies it (in which case `Poller::notified` would have been set) or when an operation needs
785 /// to occur (in which case `Poller::waiting_operations` would have been incremented).
786 event_fd: OwnedFd,
787 }
788
789 impl Notify {
790 /// Creates a new notification pipe.
791 pub(super) fn new() -> io::Result<Self> {
792 // Note that the eventfd() implementation in ESP-IDF deviates from the specification in the following ways:
793 // 1) The file descriptor is always in a non-blocking mode, as if EFD_NONBLOCK was passed as a flag;
794 // passing EFD_NONBLOCK or calling fcntl(.., F_GETFL/F_SETFL) on the eventfd() file descriptor is not supported
795 // 2) It always returns the counter value, even if it is 0. This is contrary to the specification which mandates
796 // that it should instead fail with EAGAIN
797 //
798 // (1) is not a problem for us, as we want the eventfd() file descriptor to be in a non-blocking mode anyway
799 // (2) is also not a problem, as long as we don't try to read the counter value in an endless loop when we detect being notified
800
801 let flags = EventfdFlags::empty();
802 let event_fd = eventfd(0, flags).map_err(|err| {
803 match io::Error::from(err) {
804 err if err.kind() == io::ErrorKind::PermissionDenied => {
805 // EPERM can happen if the eventfd isn't initialized yet.
806 // Tell the user to call esp_vfs_eventfd_register.
807 io::Error::new(
808 io::ErrorKind::PermissionDenied,
809 "failed to initialize eventfd for polling, try calling `esp_vfs_eventfd_register`"
810 )
811 },
812 err => err,
813 }
814 })?;
815
816 Ok(Self { event_fd })
817 }
818
819 /// Provides the eventfd file handle that needs to be registered by the `Poller`.
820 pub(super) fn fd(&self) -> BorrowedFd<'_> {
821 self.event_fd.as_fd()
822 }
823
824 /// Provides the eventfd file handle poll flags to be used when registering it with the `Poller`.
825 pub(super) fn poll_flags(&self) -> PollFlags {
826 PollFlags::IN
827 }
828
829 /// Notifies the `Poller` instance via the eventfd file descriptor.
830 pub(super) fn notify(&self) -> Result<(), io::Error> {
831 write(self.event_fd.as_fd(), &1u64.to_ne_bytes())?;
832
833 Ok(())
834 }
835
836 /// Pops a notification (if any) from the eventfd file descriptor.
837 pub(super) fn pop_notification(&self) -> Result<(), io::Error> {
838 read(self.event_fd.as_fd(), &mut [0; mem::size_of::<u64>()])?;
839
840 Ok(())
841 }
842
843 /// Pops all notifications from the eventfd file descriptor.
844 /// Since the eventfd object accumulates all writes in a single 64 bit value,
845 /// this operation is - in fact - equivalent to `pop_notification`.
846 pub(super) fn pop_all_notifications(&self) -> Result<(), io::Error> {
847 let _ = self.pop_notification();
848
849 Ok(())
850 }
851
852 /// Whether this raw file descriptor is associated with this notifier.
853 pub(super) fn has_fd(&self, fd: RawFd) -> bool {
854 self.event_fd.as_raw_fd() == fd
855 }
856 }
857 }