Skip to main content

starnix_core/task/
waiter.rs

1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::task::{CurrentTask, RunState};
6use crate::vfs::{EpollEventHandler, FdNumber};
7use bitflags::bitflags;
8use futures::stream::AbortHandle;
9use slab::Slab;
10use smallvec::SmallVec;
11use starnix_lifecycle::AtomicCounter;
12use starnix_sync::{
13    EventHandlerReadyQueueLock, EventWaitGuard, InterruptibleEvent, LockDepMutex, NotifyKind,
14    PortEvent, PortWaitResult, PortWaiterCallbacksLock, PortWaiterWaitQueuesLock,
15    WaitQueueImplLock, WaiterEventHandlerLock,
16};
17use starnix_types::ownership::debug_assert_no_local_temp_ref;
18use starnix_uapi::error;
19use starnix_uapi::errors::{EINTR, Errno};
20use starnix_uapi::signals::{SIGKILL, SigSet, Signal};
21use starnix_uapi::vfs::FdEvents;
22use std::collections::{HashMap, VecDeque};
23use std::sync::{Arc, Weak};
24use syncio::zxio::zxio_signals_t;
25use syncio::{ZxioSignals, ZxioWeak};
26
27#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq)]
28pub enum ReadyItemKey {
29    FdNumber(FdNumber),
30    Usize(usize),
31}
32
33impl From<FdNumber> for ReadyItemKey {
34    fn from(v: FdNumber) -> Self {
35        Self::FdNumber(v)
36    }
37}
38
39impl From<usize> for ReadyItemKey {
40    fn from(v: usize) -> Self {
41        Self::Usize(v)
42    }
43}
44
45#[derive(Debug, Copy, Clone)]
46pub struct ReadyItem {
47    pub key: ReadyItemKey,
48    pub events: FdEvents,
49}
50
51#[derive(Clone)]
52pub enum EventHandler {
53    /// Does nothing.
54    ///
55    /// It is up to the waiter to synchronize itself with the notifier if
56    /// synchronization is needed.
57    None,
58
59    /// Enqueues an event to a ready list.
60    ///
61    /// This event handler naturally synchronizes the notifier and notifee
62    /// because of the lock acquired/released when enqueuing the event.
63    Enqueue {
64        key: ReadyItemKey,
65        queue: Arc<LockDepMutex<VecDeque<ReadyItem>, EventHandlerReadyQueueLock>>,
66        sought_events: FdEvents,
67    },
68
69    /// Wraps another EventHandler and only triggers it once. Further .handle() calls are ignored.
70    ///
71    /// This is intended for cases like BinderFileObject which need to register
72    /// the same EventHandler on multiple wait queues.
73    HandleOnce(Arc<LockDepMutex<Option<EventHandler>, WaiterEventHandlerLock>>),
74
75    /// This handler is an epoll.
76    Epoll(EpollEventHandler),
77}
78
79impl EventHandler {
80    pub fn handle(self, events: FdEvents) {
81        match self {
82            Self::None => {}
83            Self::Enqueue { key, queue, sought_events } => {
84                let events = events & sought_events;
85                queue.lock().push_back(ReadyItem { key, events });
86            }
87            Self::HandleOnce(inner) => {
88                if let Some(inner) = inner.lock().take() {
89                    inner.handle(events);
90                }
91            }
92            Self::Epoll(e) => e.handle(events),
93        }
94    }
95}
96
97pub struct ZxioSignalHandler {
98    pub zxio: ZxioWeak,
99    pub get_events_from_zxio_signals: fn(zxio_signals_t) -> FdEvents,
100}
101
102// The counter is incremented as each handle is signaled; when the counter reaches the handle
103// count, the event handler is called with the given events.
104pub struct ManyZxHandleSignalHandler {
105    pub count: usize,
106    pub counter: Arc<AtomicCounter<usize>>,
107    pub expected_signals: zx::Signals,
108    pub events: FdEvents,
109}
110
111pub enum SignalHandlerInner {
112    None,
113    Zxio(ZxioSignalHandler),
114    ZxHandle(fn(zx::Signals) -> FdEvents),
115    ManyZxHandle(ManyZxHandleSignalHandler),
116}
117
118pub struct SignalHandler {
119    pub inner: SignalHandlerInner,
120    pub event_handler: EventHandler,
121    pub err_code: Option<Errno>,
122}
123
124impl SignalHandler {
125    fn handle(self, signals: zx::Signals) -> Option<Errno> {
126        let SignalHandler { inner, event_handler, err_code } = self;
127        let events = match inner {
128            SignalHandlerInner::None => None,
129            SignalHandlerInner::Zxio(ZxioSignalHandler { zxio, get_events_from_zxio_signals }) => {
130                if let Some(zxio) = zxio.upgrade() {
131                    Some(get_events_from_zxio_signals(zxio.wait_end(signals)))
132                } else {
133                    None
134                }
135            }
136            SignalHandlerInner::ZxHandle(get_events_from_zx_signals) => {
137                Some(get_events_from_zx_signals(signals))
138            }
139            SignalHandlerInner::ManyZxHandle(signal_handler) => {
140                if signals.contains(signal_handler.expected_signals) {
141                    let new_count = signal_handler.counter.next() + 1;
142                    assert!(new_count <= signal_handler.count);
143                    if new_count == signal_handler.count {
144                        Some(signal_handler.events)
145                    } else {
146                        None
147                    }
148                } else {
149                    None
150                }
151            }
152        };
153        if let Some(events) = events {
154            event_handler.handle(events)
155        }
156        err_code
157    }
158}
159
160pub enum WaitCallback {
161    SignalHandler(SignalHandler),
162    EventHandler(EventHandler),
163}
164
165struct WaitCancelerQueue {
166    wait_queue: Weak<LockDepMutex<WaitQueueImpl, WaitQueueImplLock>>,
167    waiter: WaiterRef,
168    wait_key: WaitKey,
169    waiter_id: WaitEntryId,
170}
171
172struct WaitCancelerZxio {
173    zxio: ZxioWeak,
174    inner: PortWaitCanceler,
175}
176
177struct WaitCancelerPort {
178    inner: PortWaitCanceler,
179}
180
181enum WaitCancelerInner {
182    Zxio(WaitCancelerZxio),
183    Queue(WaitCancelerQueue),
184    Port(WaitCancelerPort),
185}
186
187enum NotifiableRef {
188    Port(Arc<PortWaiter>),
189    Event(Arc<InterruptibleEvent>),
190    AbortHandle(Arc<AbortHandle>),
191}
192
193const WAIT_CANCELER_COMMON_SIZE: usize = 2;
194
195/// Return values for wait_async methods.
196///
197/// Calling `cancel` will cancel any running wait.
198///
199/// Does not implement `Clone` or `Copy` so that only a single canceler exists
200/// per wait.
201pub struct WaitCanceler {
202    cancellers: smallvec::SmallVec<[WaitCancelerInner; WAIT_CANCELER_COMMON_SIZE]>,
203}
204
205impl WaitCanceler {
206    fn new_inner(inner: WaitCancelerInner) -> Self {
207        Self { cancellers: smallvec::smallvec![inner] }
208    }
209
210    pub fn new_noop() -> Self {
211        Self { cancellers: Default::default() }
212    }
213
214    pub fn new_zxio(zxio: ZxioWeak, inner: PortWaitCanceler) -> Self {
215        Self::new_inner(WaitCancelerInner::Zxio(WaitCancelerZxio { zxio, inner }))
216    }
217
218    pub fn new_port(inner: PortWaitCanceler) -> Self {
219        Self::new_inner(WaitCancelerInner::Port(WaitCancelerPort { inner }))
220    }
221
222    /// Equivalent to `merge_unbounded`, except that it enforces that the resulting vector of
223    /// cancellers is small enough to avoid being separately allocated on the heap.
224    ///
225    /// If possible, use this function instead of `merge_unbounded`, because it gives us better
226    /// tools to keep this code path optimized.
227    pub fn merge(self, other: Self) -> Self {
228        // Increase `WAIT_CANCELER_COMMON_SIZE` if needed, or remove this assert and allow the
229        // smallvec to allocate.
230        assert!(
231            self.cancellers.len() + other.cancellers.len() <= WAIT_CANCELER_COMMON_SIZE,
232            "WaitCanceler::merge disallows more than {} cancellers, found {} + {}",
233            WAIT_CANCELER_COMMON_SIZE,
234            self.cancellers.len(),
235            other.cancellers.len()
236        );
237        WaitCanceler::merge_unbounded(self, other)
238    }
239
240    /// Creates a new `WaitCanceler` that is equivalent to canceling both its arguments.
241    pub fn merge_unbounded(
242        Self { mut cancellers }: Self,
243        Self { cancellers: mut other }: Self,
244    ) -> Self {
245        cancellers.append(&mut other);
246        WaitCanceler { cancellers }
247    }
248
249    /// Cancel the pending wait.
250    ///
251    /// Takes `self` by value since a wait can only be canceled once.
252    pub fn cancel(self) {
253        let Self { cancellers } = self;
254        for canceller in cancellers.into_iter().rev() {
255            match canceller {
256                WaitCancelerInner::Zxio(WaitCancelerZxio { zxio, inner }) => {
257                    let Some(zxio) = zxio.upgrade() else { return };
258                    let (_, signals) = zxio.wait_begin(ZxioSignals::NONE.bits());
259                    inner.cancel();
260                    zxio.wait_end(signals);
261                }
262                WaitCancelerInner::Queue(WaitCancelerQueue {
263                    wait_queue,
264                    waiter,
265                    wait_key,
266                    waiter_id: WaitEntryId { key, id },
267                }) => {
268                    let Some(wait_queue) = wait_queue.upgrade() else { return };
269                    waiter.remove_callback(&wait_key);
270                    waiter.will_remove_from_wait_queue(&wait_key);
271                    let mut wait_queue = wait_queue.lock();
272                    let waiters = &mut wait_queue.waiters;
273                    if let Some(entry) = waiters.get_mut(key) {
274                        // The map of waiters in a wait queue uses a `Slab` which
275                        // recycles keys. To make sure we are removing the right
276                        // entry, make sure the ID value matches what we expect
277                        // to remove.
278                        if entry.id == id {
279                            waiters.remove(key);
280                        }
281                    }
282                }
283                WaitCancelerInner::Port(WaitCancelerPort { inner }) => {
284                    inner.cancel();
285                }
286            }
287        }
288    }
289}
290
291/// Return values for wait_async methods that monitor the state of a handle.
292///
293/// Calling `cancel` will cancel any running wait.
294///
295/// Does not implement `Clone` or `Copy` so that only a single canceler exists
296/// per wait.
297pub struct PortWaitCanceler {
298    waiter: Weak<PortWaiter>,
299    key: WaitKey,
300}
301
302impl PortWaitCanceler {
303    /// Cancel the pending wait.
304    ///
305    /// Takes `self` by value since a wait can only be canceled once.
306    pub fn cancel(self) {
307        let Self { waiter, key } = self;
308        if let Some(waiter) = waiter.upgrade() {
309            let _ = waiter.port.cancel(key.raw);
310            waiter.remove_callback(&key);
311        }
312    }
313}
314
315#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
316struct WaitKey {
317    raw: u64,
318}
319
320/// The different type of event that can be waited on / triggered.
321#[derive(Clone, Copy, Debug)]
322enum WaitEvents {
323    /// All event: a wait on `All` will be woken up by all event, and a trigger on `All` will wake
324    /// every waiter.
325    All,
326    /// Wait on the set of FdEvents.
327    Fd(FdEvents),
328    /// Wait for the specified value.
329    Value(u64),
330    /// Wait for a signal in a specific mask to be received by the task.
331    SignalMask(SigSet),
332}
333
334impl WaitEvents {
335    /// Returns whether a wait on `self` should be woken up by `other`.
336    fn intercept(self: &WaitEvents, other: &WaitEvents) -> bool {
337        match (self, other) {
338            (Self::All, _) | (_, Self::All) => true,
339            (Self::Fd(m1), Self::Fd(m2)) => m1.bits() & m2.bits() != 0,
340            (Self::Value(v1), Self::Value(v2)) => v1 == v2,
341            // A SignalMask event can only be intercepted by another SignalMask event.
342            (Self::SignalMask(m1), Self::SignalMask(m2)) => m1.intersects(m2),
343            _ => false,
344        }
345    }
346}
347
348impl WaitCallback {
349    pub fn none() -> EventHandler {
350        EventHandler::None
351    }
352}
353
354bitflags! {
355    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
356    pub struct WaiterOptions: u8 {
357        /// The wait cannot be interrupted by signals.
358        const IGNORE_SIGNALS   = 1 << 0;
359
360        /// The wait is not taking place at a safe point.
361        ///
362        /// For example, the caller might be holding a lock, which could cause a deadlock if the
363        /// waiter triggers delayed releasers.
364        const UNSAFE_CALLSTACK = 1 << 1;
365    }
366}
367
368/// Implementation of Waiter. We put the Waiter data in an Arc so that WaitQueue can tell when the
369/// Waiter has been destroyed by keeping a Weak reference. But this is an implementation detail and
370/// a Waiter should have a single owner. So the Arc is hidden inside Waiter.
371struct PortWaiter {
372    port: PortEvent,
373    callbacks: LockDepMutex<HashMap<WaitKey, WaitCallback>, PortWaiterCallbacksLock>, // the key 0 is reserved for 'no handler'
374    next_key: AtomicCounter<u64>,
375    options: WaiterOptions,
376
377    /// Collection of wait queues this Waiter is waiting on, so that when the Waiter is Dropped it
378    /// can remove itself from the queues.
379    ///
380    /// This lock is nested inside the WaitQueue.waiters lock.
381    wait_queues: LockDepMutex<
382        HashMap<WaitKey, Weak<LockDepMutex<WaitQueueImpl, WaitQueueImplLock>>>,
383        PortWaiterWaitQueuesLock,
384    >,
385}
386
387impl PortWaiter {
388    /// Internal constructor.
389    fn new(options: WaiterOptions) -> Arc<Self> {
390        Arc::new(PortWaiter {
391            port: PortEvent::new(),
392            callbacks: Default::default(),
393            next_key: AtomicCounter::<u64>::new(1),
394            options,
395            wait_queues: Default::default(),
396        })
397    }
398
399    /// Waits until the given deadline has passed or the waiter is woken up. See wait_until().
400    fn wait_internal(&self, deadline: zx::MonotonicInstant) -> Result<(), Errno> {
401        // This method can block arbitrarily long, possibly waiting for another process. The
402        // current thread should not own any local ref that might delay the release of a resource
403        // while doing so.
404        debug_assert_no_local_temp_ref();
405
406        match self.port.wait(deadline) {
407            PortWaitResult::Notification { kind: NotifyKind::Regular } => Ok(()),
408            PortWaitResult::Notification { kind: NotifyKind::Interrupt } => error!(EINTR),
409            PortWaitResult::Signal { key, observed } => {
410                if let Some(callback) = self.remove_callback(&WaitKey { raw: key }) {
411                    match callback {
412                        WaitCallback::SignalHandler(handler) => {
413                            if let Some(errno) = handler.handle(observed) {
414                                return Err(errno);
415                            }
416                        }
417                        WaitCallback::EventHandler(_) => {
418                            panic!("wrong type of handler called")
419                        }
420                    }
421                }
422
423                Ok(())
424            }
425            PortWaitResult::TimedOut => error!(ETIMEDOUT),
426        }
427    }
428
429    fn wait_until(
430        self: &Arc<Self>,
431        current_task: &CurrentTask,
432        run_state: RunState,
433        deadline: zx::MonotonicInstant,
434    ) -> Result<(), Errno> {
435        let is_waiting = deadline.into_nanos() > 0;
436
437        let callback = || {
438            // We are susceptible to spurious wakeups because interrupt() posts a message to the port
439            // queue. In addition to more subtle races, there could already be valid messages in the
440            // port queue that will immediately wake us up, leaving the interrupt message in the queue
441            // for subsequent waits (which by then may not have any signals pending) to read.
442            //
443            // It's impossible to non-racily guarantee that a signal is pending so there might always
444            // be an EINTR result here with no signal. But any signal we get when !is_waiting we know is
445            // leftover from before: the top of this function only sets ourself as the
446            // current_task.signals.run_state when there's a nonzero timeout, and that waiter reference
447            // is what is used to signal the interrupt().
448            loop {
449                let wait_result = self.wait_internal(deadline);
450                if let Err(errno) = &wait_result {
451                    if errno.code == EINTR && !is_waiting {
452                        continue; // Spurious wakeup.
453                    }
454                }
455                return wait_result;
456            }
457        };
458
459        // Trigger delayed releaser before blocking if we're at a safe point.
460        //
461        // For example, we cannot trigger delayed releaser if we are holding any locks.
462        if !self.options.contains(WaiterOptions::UNSAFE_CALLSTACK) {
463            current_task.trigger_delayed_releaser();
464        }
465
466        if is_waiting { current_task.run_in_state(run_state, callback) } else { callback() }
467    }
468
469    fn next_key(&self) -> WaitKey {
470        let key = self.next_key.next();
471        // TODO - find a better reaction to wraparound
472        assert!(key != 0, "bad key from u64 wraparound");
473        WaitKey { raw: key }
474    }
475
476    fn register_callback(&self, callback: WaitCallback) -> WaitKey {
477        let key = self.next_key();
478        assert!(
479            self.callbacks.lock().insert(key, callback).is_none(),
480            "unexpected callback already present for key {key:?}"
481        );
482        key
483    }
484
485    fn remove_callback(&self, key: &WaitKey) -> Option<WaitCallback> {
486        self.callbacks.lock().remove(&key)
487    }
488
489    fn wake_immediately(&self, events: FdEvents, handler: EventHandler) {
490        let callback = WaitCallback::EventHandler(handler);
491        let key = self.register_callback(callback);
492        self.queue_events(&key, WaitEvents::Fd(events));
493    }
494
495    /// Establish an asynchronous wait for the signals on the given Zircon handle (not to be
496    /// confused with POSIX signals), optionally running a FnOnce. Wait operations will return
497    /// the error code present in the provided SignalHandler.
498    ///
499    /// Returns a `PortWaitCanceler` that can be used to cancel the wait.
500    fn wake_on_zircon_signals(
501        self: &Arc<Self>,
502        handle: &dyn zx::AsHandleRef,
503        zx_signals: zx::Signals,
504        handler: SignalHandler,
505    ) -> Result<PortWaitCanceler, zx::Status> {
506        let callback = WaitCallback::SignalHandler(handler);
507        let key = self.register_callback(callback);
508        self.port.object_wait_async(
509            handle,
510            key.raw,
511            zx_signals,
512            zx::WaitAsyncOpts::EDGE_TRIGGERED,
513        )?;
514        Ok(PortWaitCanceler { waiter: Arc::downgrade(self), key })
515    }
516
517    fn queue_events(&self, key: &WaitKey, events: WaitEvents) {
518        scopeguard::defer! {
519            self.port.notify(NotifyKind::Regular)
520        }
521
522        // Handling user events immediately when they are triggered breaks any
523        // ordering expectations on Linux by batching all starnix events with
524        // the first starnix event even if other events occur on the Fuchsia
525        // platform (and are enqueued to the `zx::Port`) between them. This
526        // ordering does not seem to be load-bearing for applications running on
527        // starnix so we take the divergence in ordering in favour of improved
528        // performance (by minimizing syscalls) when operating on FDs backed by
529        // starnix.
530        //
531        // TODO(https://fxbug.dev/42084319): If we can read a batch of packets
532        // from the `zx::Port`, maybe we can keep the ordering?
533        let Some(callback) = self.remove_callback(key) else {
534            return;
535        };
536
537        match callback {
538            WaitCallback::EventHandler(handler) => {
539                let events = match events {
540                    // If the event is All, signal on all possible fd
541                    // events.
542                    WaitEvents::All => FdEvents::all(),
543                    WaitEvents::Fd(events) => events,
544                    WaitEvents::SignalMask(_) => FdEvents::POLLIN,
545                    WaitEvents::Value(_) => FdEvents::POLLIN,
546                };
547                handler.handle(events)
548            }
549            WaitCallback::SignalHandler(_) => {
550                panic!("wrong type of handler called")
551            }
552        }
553    }
554
555    fn notify(&self) {
556        self.port.notify(NotifyKind::Regular);
557    }
558
559    fn interrupt(&self) {
560        if self.options.contains(WaiterOptions::IGNORE_SIGNALS) {
561            return;
562        }
563        self.port.notify(NotifyKind::Interrupt);
564    }
565}
566
567impl std::fmt::Debug for PortWaiter {
568    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
569        f.debug_struct("PortWaiter").field("port", &self.port).finish_non_exhaustive()
570    }
571}
572
573/// A type that can put a thread to sleep waiting for a condition.
574#[derive(Debug, Clone)]
575pub struct Waiter {
576    // TODO(https://g-issues.fuchsia.dev/issues/303068424): Avoid `PortWaiter`
577    // when operating purely over FDs backed by starnix.
578    inner: Arc<PortWaiter>,
579}
580
581impl Waiter {
582    /// Create a new waiter.
583    pub fn new() -> Self {
584        Self { inner: PortWaiter::new(WaiterOptions::empty()) }
585    }
586
587    /// Create a new waiter with the given options.
588    pub fn with_options(options: WaiterOptions) -> Self {
589        Self { inner: PortWaiter::new(options) }
590    }
591
592    /// Create a weak reference to this waiter.
593    fn weak(&self) -> WaiterRef {
594        WaiterRef::from_port(&self.inner)
595    }
596
597    /// Freeze the task until the waiter is woken up.
598    ///
599    /// No signal, e.g. EINTR (interrupt), should be received.
600    pub fn freeze(&self, current_task: &CurrentTask) {
601        while self
602            .inner
603            .wait_until(
604                current_task,
605                RunState::Frozen(self.clone()),
606                zx::MonotonicInstant::INFINITE,
607            )
608            .is_err()
609        {
610            // Avoid attempting to freeze the task if there is a pending SIGKILL.
611            if current_task.read().has_signal_pending(SIGKILL) {
612                break;
613            }
614            // Ignore spurious wakeups from the [`PortEvent.futex`]
615        }
616    }
617
618    /// Wait until the waiter is woken up.
619    ///
620    /// If the wait is interrupted (see [`Waiter::interrupt`]), this function returns EINTR.
621    pub fn wait(&self, current_task: &CurrentTask) -> Result<(), Errno> {
622        self.inner.wait_until(
623            current_task,
624            RunState::Waiter(WaiterRef::from_port(&self.inner)),
625            zx::MonotonicInstant::INFINITE,
626        )
627    }
628
629    /// Wait until the given deadline has passed or the waiter is woken up.
630    ///
631    /// If the wait deadline is nonzero and is interrupted (see [`Waiter::interrupt`]), this
632    /// function returns EINTR. Callers must take special care not to lose any accumulated data or
633    /// local state when EINTR is received as this is a normal and recoverable situation.
634    ///
635    /// Using a 0 deadline (no waiting, useful for draining pending events) will not wait and is
636    /// guaranteed not to issue EINTR.
637    ///
638    /// It the timeout elapses with no events, this function returns ETIMEDOUT.
639    ///
640    /// Processes at most one event. If the caller is interested in draining the events, it should
641    /// repeatedly call this function with a 0 deadline until it reports ETIMEDOUT. (This case is
642    /// why a 0 deadline must not return EINTR, as previous calls to wait_until() may have
643    /// accumulated state that would be lost when returning EINTR to userspace.)
644    ///
645    /// It is up to the caller (the "waiter") to make sure that it synchronizes with any object
646    /// that triggers an event (the "notifier"). This `Waiter` does not provide any synchronization
647    /// itself. Note that synchronization between the "waiter" the "notifier" may be provided by
648    /// the [`EventHandler`] used to handle an event iff the waiter observes the side-effects of
649    /// the handler (e.g. reading the ready list modified by [`EventHandler::Enqueue`] or
650    /// [`EventHandler::EnqueueOnce`]).
651    pub fn wait_until(
652        &self,
653        current_task: &CurrentTask,
654        deadline: zx::MonotonicInstant,
655    ) -> Result<(), Errno> {
656        self.inner.wait_until(
657            current_task,
658            RunState::Waiter(WaiterRef::from_port(&self.inner)),
659            deadline,
660        )
661    }
662
663    fn create_wait_entry(&self, filter: WaitEvents) -> WaitEntry {
664        WaitEntry { waiter: self.weak(), filter, key: self.inner.next_key() }
665    }
666
667    fn create_wait_entry_with_handler(
668        &self,
669        filter: WaitEvents,
670        handler: EventHandler,
671    ) -> WaitEntry {
672        let key = self.inner.register_callback(WaitCallback::EventHandler(handler));
673        WaitEntry { waiter: self.weak(), filter, key }
674    }
675
676    pub fn wake_immediately(&self, events: FdEvents, handler: EventHandler) {
677        self.inner.wake_immediately(events, handler);
678    }
679
680    /// Establish an asynchronous wait for the signals on the given Zircon handle (not to be
681    /// confused with POSIX signals), optionally running a FnOnce.
682    ///
683    /// Returns a `PortWaitCanceler` that can be used to cancel the wait.
684    pub fn wake_on_zircon_signals(
685        &self,
686        handle: &dyn zx::AsHandleRef,
687        zx_signals: zx::Signals,
688        handler: SignalHandler,
689    ) -> Result<PortWaitCanceler, zx::Status> {
690        self.inner.wake_on_zircon_signals(handle, zx_signals, handler)
691    }
692
693    /// Return a WaitCanceler representing a wait that will never complete. Useful for stub
694    /// implementations that should block forever even though a real implementation would wake up
695    /// eventually.
696    pub fn fake_wait(&self) -> WaitCanceler {
697        WaitCanceler::new_noop()
698    }
699
700    // Notify the waiter to wake it up without signalling any events.
701    pub fn notify(&self) {
702        self.inner.notify();
703    }
704
705    /// Interrupt the waiter to deliver a signal. The wait operation will return EINTR, and a
706    /// typical caller should then unwind to the syscall dispatch loop to let the signal be
707    /// processed. See wait_until() for more details.
708    ///
709    /// Ignored if the waiter was created with new_ignoring_signals().
710    pub fn interrupt(&self) {
711        self.inner.interrupt();
712    }
713}
714
715impl Drop for Waiter {
716    fn drop(&mut self) {
717        // Delete ourselves from each wait queue we know we're on to prevent Weak references to
718        // ourself from sticking around forever.
719        let wait_queues = std::mem::take(&mut *self.inner.wait_queues.lock()).into_values();
720        for wait_queue in wait_queues {
721            if let Some(wait_queue) = wait_queue.upgrade() {
722                wait_queue.lock().waiters.retain(|_, entry| entry.entry.waiter != *self)
723            }
724        }
725    }
726}
727
728impl Default for Waiter {
729    fn default() -> Self {
730        Self::new()
731    }
732}
733
734impl PartialEq for Waiter {
735    fn eq(&self, other: &Self) -> bool {
736        Arc::ptr_eq(&self.inner, &other.inner)
737    }
738}
739
740pub struct SimpleWaiter {
741    event: Arc<InterruptibleEvent>,
742    wait_queues: Vec<Weak<LockDepMutex<WaitQueueImpl, WaitQueueImplLock>>>,
743}
744
745impl SimpleWaiter {
746    pub fn new(event: &Arc<InterruptibleEvent>) -> (SimpleWaiter, EventWaitGuard<'_>) {
747        (SimpleWaiter { event: event.clone(), wait_queues: Default::default() }, event.begin_wait())
748    }
749}
750
751impl Drop for SimpleWaiter {
752    fn drop(&mut self) {
753        for wait_queue in &self.wait_queues {
754            if let Some(wait_queue) = wait_queue.upgrade() {
755                wait_queue.lock().waiters.retain(|_, entry| entry.entry.waiter != self.event)
756            }
757        }
758    }
759}
760
761#[derive(Debug, Clone)]
762enum WaiterKind {
763    Port(Weak<PortWaiter>),
764    Event(Weak<InterruptibleEvent>),
765    AbortHandle(Weak<futures::stream::AbortHandle>),
766}
767
768impl Default for WaiterKind {
769    fn default() -> Self {
770        WaiterKind::Port(Default::default())
771    }
772}
773
774/// A weak reference to a Waiter. Intended for holding in wait queues or stashing elsewhere for
775/// calling queue_events later.
776#[derive(Debug, Default, Clone)]
777pub struct WaiterRef(WaiterKind);
778
779impl WaiterRef {
780    fn from_port(waiter: &Arc<PortWaiter>) -> WaiterRef {
781        WaiterRef(WaiterKind::Port(Arc::downgrade(waiter)))
782    }
783
784    fn from_event(event: &Arc<InterruptibleEvent>) -> WaiterRef {
785        WaiterRef(WaiterKind::Event(Arc::downgrade(event)))
786    }
787
788    pub fn from_abort_handle(handle: &Arc<futures::stream::AbortHandle>) -> WaiterRef {
789        WaiterRef(WaiterKind::AbortHandle(Arc::downgrade(handle)))
790    }
791
792    pub fn is_valid(&self) -> bool {
793        match &self.0 {
794            WaiterKind::Port(waiter) => waiter.strong_count() != 0,
795            WaiterKind::Event(event) => event.strong_count() != 0,
796            WaiterKind::AbortHandle(handle) => handle.strong_count() != 0,
797        }
798    }
799
800    pub fn interrupt(&self) {
801        match &self.0 {
802            WaiterKind::Port(waiter) => {
803                if let Some(waiter) = waiter.upgrade() {
804                    waiter.interrupt();
805                }
806            }
807            WaiterKind::Event(event) => {
808                if let Some(event) = event.upgrade() {
809                    event.interrupt();
810                }
811            }
812            WaiterKind::AbortHandle(handle) => {
813                if let Some(handle) = handle.upgrade() {
814                    handle.abort();
815                }
816            }
817        }
818    }
819
820    fn remove_callback(&self, key: &WaitKey) {
821        match &self.0 {
822            WaiterKind::Port(waiter) => {
823                if let Some(waiter) = waiter.upgrade() {
824                    waiter.remove_callback(key);
825                }
826            }
827            _ => (),
828        }
829    }
830
831    /// Attempts to upgrade a waiter ref to a notifiable ref. If the waiter ref is no
832    /// longer valid, returns None.
833    fn upgrade_notifiable(&self) -> Option<NotifiableRef> {
834        match &self.0 {
835            WaiterKind::Port(waiter) => {
836                if let Some(waiter) = waiter.upgrade() {
837                    return Some(NotifiableRef::Port(waiter));
838                }
839            }
840            WaiterKind::Event(event) => {
841                if let Some(event) = event.upgrade() {
842                    return Some(NotifiableRef::Event(event));
843                }
844            }
845            WaiterKind::AbortHandle(handle) => {
846                if let Some(handle) = handle.upgrade() {
847                    return Some(NotifiableRef::AbortHandle(handle));
848                }
849            }
850        }
851        None
852    }
853
854    /// Called by the WaitQueue when this waiter is about to be removed from the queue.
855    ///
856    /// TODO(abarth): This function does not appear to be called when the WaitQueue is dropped,
857    /// which appears to be a leak.
858    fn will_remove_from_wait_queue(&self, key: &WaitKey) {
859        match &self.0 {
860            WaiterKind::Port(waiter) => {
861                if let Some(waiter) = waiter.upgrade() {
862                    waiter.wait_queues.lock().remove(key);
863                }
864            }
865            _ => (),
866        }
867    }
868}
869
870impl PartialEq<Waiter> for WaiterRef {
871    fn eq(&self, other: &Waiter) -> bool {
872        match &self.0 {
873            WaiterKind::Port(waiter) => waiter.as_ptr() == Arc::as_ptr(&other.inner),
874            _ => false,
875        }
876    }
877}
878
879impl PartialEq<Arc<InterruptibleEvent>> for WaiterRef {
880    fn eq(&self, other: &Arc<InterruptibleEvent>) -> bool {
881        match &self.0 {
882            WaiterKind::Event(event) => event.as_ptr() == Arc::as_ptr(other),
883            _ => false,
884        }
885    }
886}
887
888impl PartialEq for WaiterRef {
889    fn eq(&self, other: &WaiterRef) -> bool {
890        match (&self.0, &other.0) {
891            (WaiterKind::Port(lhs), WaiterKind::Port(rhs)) => Weak::ptr_eq(lhs, rhs),
892            (WaiterKind::Event(lhs), WaiterKind::Event(rhs)) => Weak::ptr_eq(lhs, rhs),
893            (WaiterKind::AbortHandle(lhs), WaiterKind::AbortHandle(rhs)) => Weak::ptr_eq(lhs, rhs),
894            _ => false,
895        }
896    }
897}
898
899impl NotifiableRef {
900    fn notify(&self, key: &WaitKey, events: WaitEvents) {
901        match self {
902            NotifiableRef::Port(port_waiter) => port_waiter.queue_events(key, events),
903            NotifiableRef::Event(interruptible_event) => interruptible_event.notify(),
904            NotifiableRef::AbortHandle(handle) => handle.abort(),
905        }
906    }
907}
908
909/// A list of waiters waiting for some event.
910///
911/// For events that are generated inside Starnix, we walk the wait queue
912/// on the thread that triggered the event to notify the waiters that the event
913/// has occurred. The waiters will then wake up on their own thread to handle
914/// the event.
915#[derive(Default, Debug, Clone)]
916pub struct WaitQueue(Arc<LockDepMutex<WaitQueueImpl, WaitQueueImplLock>>);
917
918impl WaitQueue {
919    pub fn new() -> Self {
920        Self(Arc::new(WaitQueueImpl::default().into()))
921    }
922}
923
924#[derive(Debug)]
925struct WaitEntryWithId {
926    entry: WaitEntry,
927    /// The ID use to uniquely identify this wait entry even if it shares the
928    /// key used in the wait queue's [`Slab`] with another wait entry since a
929    /// slab's keys are recycled.
930    id: u64,
931}
932
933struct WaitEntryId {
934    key: usize,
935    id: u64,
936}
937
938#[derive(Default, Debug)]
939struct WaitQueueImpl {
940    /// Holds the next ID value to use when adding a new `WaitEntry` to the
941    /// waiters (dense) map.
942    ///
943    /// A [`Slab`]s keys are recycled so we use the ID to uniquely identify a
944    /// wait entry.
945    next_wait_entry_id: u64,
946    /// The list of waiters.
947    ///
948    /// The waiter's wait_queues lock is nested inside this lock.
949    waiters: Slab<WaitEntryWithId>,
950}
951
952/// An entry in a WaitQueue.
953#[derive(Debug)]
954struct WaitEntry {
955    /// The waiter that is waking for the FdEvent.
956    waiter: WaiterRef,
957
958    /// The events that the waiter is waiting for.
959    filter: WaitEvents,
960
961    /// key for cancelling and queueing events
962    key: WaitKey,
963}
964
965impl WaitQueue {
966    fn add_waiter(&self, entry: WaitEntry) -> WaitEntryId {
967        let mut wait_queue = self.0.lock();
968        let id = wait_queue
969            .next_wait_entry_id
970            .checked_add(1)
971            .expect("all possible wait entry ID values exhausted");
972        wait_queue.next_wait_entry_id = id;
973        WaitEntryId { key: wait_queue.waiters.insert(WaitEntryWithId { entry, id }), id }
974    }
975
976    /// Establish a wait for the given entry.
977    ///
978    /// The waiter will be notified when an event matching the entry occurs.
979    ///
980    /// This function does not actually block the waiter. To block the waiter,
981    /// call the [`Waiter::wait`] function on the waiter.
982    ///
983    /// Returns a `WaitCanceler` that can be used to cancel the wait.
984    fn wait_async_entry(&self, waiter: &Waiter, entry: WaitEntry) -> WaitCanceler {
985        let wait_key = entry.key;
986        let waiter_id = self.add_waiter(entry);
987        let wait_queue = Arc::downgrade(&self.0);
988        waiter.inner.wait_queues.lock().insert(wait_key, wait_queue.clone());
989        WaitCanceler::new_inner(WaitCancelerInner::Queue(WaitCancelerQueue {
990            wait_queue,
991            waiter: waiter.weak(),
992            wait_key,
993            waiter_id,
994        }))
995    }
996
997    /// Establish a wait for the given value event.
998    ///
999    /// The waiter will be notified when an event with the same value occurs.
1000    ///
1001    /// This function does not actually block the waiter. To block the waiter,
1002    /// call the [`Waiter::wait`] function on the waiter.
1003    ///
1004    /// Returns a `WaitCanceler` that can be used to cancel the wait.
1005    pub fn wait_async_value(&self, waiter: &Waiter, value: u64) -> WaitCanceler {
1006        self.wait_async_entry(waiter, waiter.create_wait_entry(WaitEvents::Value(value)))
1007    }
1008
1009    /// Establish a wait for the given value event with an associated handler.
1010    ///
1011    /// The waiter will be notified when an event with the same value occurs, triggering the handler.
1012    ///
1013    /// This function does not actually block the waiter. To block the waiter,
1014    /// call the [`Waiter::wait`] function on the waiter.
1015    ///
1016    /// Returns a `WaitCanceler` that can be used to cancel the wait.
1017    pub fn wait_async_value_with_handler(
1018        &self,
1019        waiter: &Waiter,
1020        value: u64,
1021        handler: EventHandler,
1022    ) -> WaitCanceler {
1023        let entry = waiter.create_wait_entry_with_handler(WaitEvents::Value(value), handler);
1024        self.wait_async_entry(waiter, entry)
1025    }
1026
1027    /// Establish a wait for the given FdEvents.
1028    ///
1029    /// The waiter will be notified when an event matching the `events` occurs.
1030    ///
1031    /// This function does not actually block the waiter. To block the waiter,
1032    /// call the [`Waiter::wait`] function on the waiter.
1033    ///
1034    /// Returns a `WaitCanceler` that can be used to cancel the wait.
1035    pub fn wait_async_fd_events(
1036        &self,
1037        waiter: &Waiter,
1038        events: FdEvents,
1039        handler: EventHandler,
1040    ) -> WaitCanceler {
1041        let entry = waiter.create_wait_entry_with_handler(WaitEvents::Fd(events), handler);
1042        self.wait_async_entry(waiter, entry)
1043    }
1044
1045    /// Establish a wait for a particular signal mask.
1046    ///
1047    /// The waiter will be notified when a signal in the mask is received.
1048    ///
1049    /// This function does not actually block the waiter. To block the waiter,
1050    /// call the [`Waiter::wait`] function on the waiter.
1051    ///
1052    /// Returns a `WaitCanceler` that can be used to cancel the wait.
1053    pub fn wait_async_signal_mask(
1054        &self,
1055        waiter: &Waiter,
1056        mask: SigSet,
1057        handler: EventHandler,
1058    ) -> WaitCanceler {
1059        let entry = waiter.create_wait_entry_with_handler(WaitEvents::SignalMask(mask), handler);
1060        self.wait_async_entry(waiter, entry)
1061    }
1062
1063    /// Establish a wait for any event.
1064    ///
1065    /// The waiter will be notified when any event occurs.
1066    ///
1067    /// This function does not actually block the waiter. To block the waiter,
1068    /// call the [`Waiter::wait`] function on the waiter.
1069    ///
1070    /// Returns a `WaitCanceler` that can be used to cancel the wait.
1071    pub fn wait_async(&self, waiter: &Waiter) -> WaitCanceler {
1072        self.wait_async_entry(waiter, waiter.create_wait_entry(WaitEvents::All))
1073    }
1074
1075    pub fn wait_async_simple(&self, waiter: &mut SimpleWaiter) {
1076        let entry = WaitEntry {
1077            waiter: WaiterRef::from_event(&waiter.event),
1078            filter: WaitEvents::All,
1079            key: Default::default(),
1080        };
1081        waiter.wait_queues.push(Arc::downgrade(&self.0));
1082        self.add_waiter(entry);
1083    }
1084
1085    fn notify_events_count(&self, mut events: WaitEvents, mut limit: usize) -> usize {
1086        if let WaitEvents::Fd(ref mut fd_events) = events {
1087            *fd_events = fd_events.add_equivalent_fd_events();
1088        }
1089        // Store references to waiters ready to be notified locally so that we can drop our waiters
1090        // lock before notifying the waiters. The waiters will need to acquire the waiters lock once
1091        // they wake up in order to remove themselves from the queue and so they might contend
1092        // with this thread for that lock.
1093        // Usually we expect to notify at most a single waiter.
1094        let mut notifiable_refs = SmallVec::<[(NotifiableRef, WaitKey); 1]>::new();
1095        let mut woken = 0;
1096        {
1097            let mut guard = self.0.lock();
1098            guard.waiters.retain(|_, WaitEntryWithId { entry, id: _ }| {
1099                if limit > 0 && entry.filter.intercept(&events) {
1100                    if let Some(notifiable_ref) = entry.waiter.upgrade_notifiable() {
1101                        limit -= 1;
1102                        woken += 1;
1103                        notifiable_refs.push((notifiable_ref, entry.key));
1104                    }
1105
1106                    entry.waiter.will_remove_from_wait_queue(&entry.key);
1107                    false
1108                } else {
1109                    true
1110                }
1111            });
1112        }
1113        for (notifiable_ref, key) in notifiable_refs {
1114            notifiable_ref.notify(&key, events);
1115        }
1116        woken
1117    }
1118
1119    pub fn notify_fd_events(&self, events: FdEvents) {
1120        self.notify_events_count(WaitEvents::Fd(events), usize::MAX);
1121    }
1122
1123    pub fn notify_fd_events_count(&self, events: FdEvents, limit: usize) {
1124        self.notify_events_count(WaitEvents::Fd(events), limit);
1125    }
1126
1127    pub fn notify_signal(&self, signal: &Signal) {
1128        let event = WaitEvents::SignalMask(SigSet::from(*signal));
1129        self.notify_events_count(event, usize::MAX);
1130    }
1131
1132    pub fn notify_value(&self, value: u64) {
1133        self.notify_events_count(WaitEvents::Value(value), usize::MAX);
1134    }
1135
1136    pub fn notify_unordered_count(&self, limit: usize) {
1137        self.notify_events_count(WaitEvents::All, limit);
1138    }
1139
1140    pub fn notify_all(&self) {
1141        self.notify_unordered_count(usize::MAX);
1142    }
1143
1144    /// Returns whether there is no active waiters waiting on this `WaitQueue`.
1145    pub fn is_empty(&self) -> bool {
1146        self.0.lock().waiters.is_empty()
1147    }
1148}
1149
1150/// A wait queue that dispatches events based on the value of an enum.
1151pub struct TypedWaitQueue<T: Into<u64>> {
1152    wait_queue: WaitQueue,
1153    value_type: std::marker::PhantomData<T>,
1154}
1155
1156// We can't #[derive(Default)] on [TypedWaitQueue<T>] as T may not implement the Default trait.
1157impl<T: Into<u64>> Default for TypedWaitQueue<T> {
1158    fn default() -> Self {
1159        Self { wait_queue: Default::default(), value_type: Default::default() }
1160    }
1161}
1162
1163impl<T: Into<u64>> TypedWaitQueue<T> {
1164    pub fn wait_async_value(&self, waiter: &Waiter, value: T) -> WaitCanceler {
1165        self.wait_queue.wait_async_value(waiter, value.into())
1166    }
1167
1168    pub fn wait_async_value_with_handler(
1169        &self,
1170        waiter: &Waiter,
1171        value: T,
1172        handler: EventHandler,
1173    ) -> WaitCanceler {
1174        self.wait_queue.wait_async_value_with_handler(waiter, value.into(), handler)
1175    }
1176
1177    pub fn notify_value(&self, value: T) {
1178        self.wait_queue.notify_value(value.into())
1179    }
1180}
1181
1182#[cfg(test)]
1183mod tests {
1184    use super::*;
1185    use crate::fs::fuchsia::create_fuchsia_pipe;
1186    use crate::signals::SignalInfo;
1187    use crate::task::TaskFlags;
1188    use crate::testing::{spawn_kernel_and_run, spawn_kernel_and_run_sync};
1189    use crate::vfs::buffers::{VecInputBuffer, VecOutputBuffer};
1190    use crate::vfs::eventfd::{EventFdType, new_eventfd};
1191    use assert_matches::assert_matches;
1192    use starnix_uapi::open_flags::OpenFlags;
1193    use starnix_uapi::signals::SIGUSR1;
1194
1195    const KEY: ReadyItemKey = ReadyItemKey::Usize(1234);
1196
1197    #[::fuchsia::test]
1198    async fn test_async_wait_exec() {
1199        spawn_kernel_and_run(async |current_task| {
1200            let (local_socket, remote_socket) = zx::Socket::create_stream();
1201            let pipe = create_fuchsia_pipe(&current_task, remote_socket, OpenFlags::RDWR).unwrap();
1202
1203            const MEM_SIZE: usize = 1024;
1204            let mut output_buffer = VecOutputBuffer::new(MEM_SIZE);
1205
1206            let test_string = "hello startnix".to_string();
1207            let queue: Arc<LockDepMutex<VecDeque<ReadyItem>, EventHandlerReadyQueueLock>> =
1208                Default::default();
1209            let handler = EventHandler::Enqueue {
1210                key: KEY,
1211                queue: queue.clone(),
1212                sought_events: FdEvents::all(),
1213            };
1214            let waiter = Waiter::new();
1215            pipe.wait_async(&current_task, &waiter, FdEvents::POLLIN, handler).expect("wait_async");
1216            let test_string_clone = test_string.clone();
1217
1218            let write_count = AtomicCounter::<usize>::default();
1219            std::thread::scope(|s| {
1220                let thread = s.spawn(|| {
1221                    let test_data = test_string_clone.as_bytes();
1222                    let no_written = local_socket.write(test_data).unwrap();
1223                    assert_eq!(0, write_count.add(no_written));
1224                    assert_eq!(no_written, test_data.len());
1225                });
1226
1227                // this code would block on failure
1228
1229                assert!(queue.lock().is_empty());
1230                waiter.wait(&current_task).unwrap();
1231                thread.join().expect("join thread")
1232            });
1233            queue.lock().iter().for_each(|item| assert!(item.events.contains(FdEvents::POLLIN)));
1234
1235            let read_size = pipe.read(&current_task, &mut output_buffer).unwrap();
1236
1237            let no_written = write_count.get();
1238            assert_eq!(no_written, read_size);
1239
1240            assert_eq!(output_buffer.data(), test_string.as_bytes());
1241        })
1242        .await;
1243    }
1244
1245    #[::fuchsia::test]
1246    async fn test_async_wait_cancel() {
1247        for do_cancel in [true, false] {
1248            spawn_kernel_and_run(async move |current_task| {
1249                let event = new_eventfd(&current_task, 0, EventFdType::Counter, true);
1250                let waiter = Waiter::new();
1251                let queue: Arc<LockDepMutex<VecDeque<ReadyItem>, EventHandlerReadyQueueLock>> =
1252                    Default::default();
1253                let handler = EventHandler::Enqueue {
1254                    key: KEY,
1255                    queue: queue.clone(),
1256                    sought_events: FdEvents::all(),
1257                };
1258                let wait_canceler = event
1259                    .wait_async(&current_task, &waiter, FdEvents::POLLIN, handler)
1260                    .expect("wait_async");
1261                if do_cancel {
1262                    wait_canceler.cancel();
1263                }
1264                let add_val = 1u64;
1265                assert_eq!(
1266                    event
1267                        .write(&current_task, &mut VecInputBuffer::new(&add_val.to_ne_bytes()))
1268                        .unwrap(),
1269                    std::mem::size_of::<u64>()
1270                );
1271
1272                let wait_result = waiter.wait_until(&current_task, zx::MonotonicInstant::ZERO);
1273                let final_count = queue.lock().len();
1274                if do_cancel {
1275                    assert_eq!(wait_result, error!(ETIMEDOUT));
1276                    assert_eq!(0, final_count);
1277                } else {
1278                    assert_eq!(wait_result, Ok(()));
1279                    assert_eq!(1, final_count);
1280                }
1281            })
1282            .await;
1283        }
1284    }
1285
1286    #[::fuchsia::test]
1287    async fn single_waiter_multiple_waits_cancel_one_waiter_still_notified() {
1288        spawn_kernel_and_run(async |current_task| {
1289            let wait_queue = WaitQueue::default();
1290            let waiter = Waiter::new();
1291            let wk1 = wait_queue.wait_async(&waiter);
1292            let _wk2 = wait_queue.wait_async(&waiter);
1293            wk1.cancel();
1294            wait_queue.notify_all();
1295            assert!(waiter.wait_until(&current_task, zx::MonotonicInstant::ZERO).is_ok());
1296        })
1297        .await;
1298    }
1299
1300    #[::fuchsia::test]
1301    async fn multiple_waiters_cancel_one_other_still_notified() {
1302        spawn_kernel_and_run(async |current_task| {
1303            let wait_queue = WaitQueue::default();
1304            let waiter1 = Waiter::new();
1305            let waiter2 = Waiter::new();
1306            let wk1 = wait_queue.wait_async(&waiter1);
1307            let _wk2 = wait_queue.wait_async(&waiter2);
1308            wk1.cancel();
1309            wait_queue.notify_all();
1310            assert!(waiter1.wait_until(&current_task, zx::MonotonicInstant::ZERO).is_err());
1311            assert!(waiter2.wait_until(&current_task, zx::MonotonicInstant::ZERO).is_ok());
1312        })
1313        .await;
1314    }
1315
1316    #[::fuchsia::test]
1317    async fn test_wait_queue() {
1318        spawn_kernel_and_run(async |current_task| {
1319            let queue = WaitQueue::default();
1320
1321            let waiters = <[Waiter; 3]>::default();
1322            waiters.iter().for_each(|w| {
1323                queue.wait_async(w);
1324            });
1325
1326            let woken = || {
1327                waiters
1328                    .iter()
1329                    .filter(|w| w.wait_until(&current_task, zx::MonotonicInstant::ZERO).is_ok())
1330                    .count()
1331            };
1332
1333            const INITIAL_NOTIFY_COUNT: usize = 2;
1334            let total_waiters = waiters.len();
1335            queue.notify_unordered_count(INITIAL_NOTIFY_COUNT);
1336            assert_eq!(INITIAL_NOTIFY_COUNT, woken());
1337
1338            // Only the remaining (unnotified) waiters should be notified.
1339            queue.notify_all();
1340            assert_eq!(total_waiters - INITIAL_NOTIFY_COUNT, woken());
1341        })
1342        .await;
1343    }
1344
1345    #[::fuchsia::test]
1346    async fn waiter_kind_abort_handle() {
1347        spawn_kernel_and_run_sync(|current_task| {
1348            let mut executor = fuchsia_async::TestExecutor::new();
1349            let (abort_handle, abort_registration) = futures::stream::AbortHandle::new_pair();
1350            let abort_handle = Arc::new(abort_handle);
1351            let waiter_ref = WaiterRef::from_abort_handle(&abort_handle);
1352
1353            let mut fut = futures::stream::Abortable::new(
1354                futures::future::pending::<()>(),
1355                abort_registration,
1356            );
1357
1358            assert_matches!(executor.run_until_stalled(&mut fut), std::task::Poll::Pending);
1359
1360            waiter_ref.interrupt();
1361            let output = current_task.run_in_state(RunState::Waiter(waiter_ref), move || {
1362                match executor.run_singlethreaded(&mut fut) {
1363                    Ok(()) => unreachable!("future never terminates normally"),
1364                    Err(futures::stream::Aborted) => Ok(()),
1365                }
1366            });
1367
1368            assert_eq!(output, Ok(()));
1369        })
1370        .await;
1371    }
1372
1373    #[::fuchsia::test]
1374    async fn freeze_with_pending_sigusr1() {
1375        spawn_kernel_and_run(async |current_task| {
1376            {
1377                let mut task_state = current_task.task.write();
1378                let siginfo = SignalInfo::kernel(SIGUSR1);
1379                task_state.enqueue_signal(siginfo);
1380                task_state.set_flags(TaskFlags::SIGNALS_AVAILABLE, true);
1381            }
1382
1383            let output: Result<(), Errno> = current_task
1384                .run_in_state(RunState::Event(InterruptibleEvent::new()), move || {
1385                    unreachable!("callback should not be called")
1386                });
1387            assert_eq!(output, error!(EINTR));
1388
1389            let output = current_task.run_in_state(RunState::Frozen(Waiter::new()), move || Ok(()));
1390            assert_eq!(output, Ok(()));
1391        })
1392        .await;
1393    }
1394
1395    #[::fuchsia::test]
1396    async fn freeze_with_pending_sigkill() {
1397        spawn_kernel_and_run(async |current_task| {
1398            {
1399                let mut task_state = current_task.task.write();
1400                let siginfo = SignalInfo::kernel(SIGKILL);
1401                task_state.enqueue_signal(siginfo);
1402                task_state.set_flags(TaskFlags::SIGNALS_AVAILABLE, true);
1403            }
1404
1405            let output: Result<(), _> = current_task
1406                .run_in_state(RunState::Frozen(Waiter::new()), move || {
1407                    unreachable!("callback should not be called")
1408                });
1409            assert_eq!(output, error!(EINTR));
1410        })
1411        .await;
1412    }
1413
1414    #[::fuchsia::test]
1415    async fn test_async_typed_wait_value_with_handler() {
1416        spawn_kernel_and_run(async |current_task| {
1417            let queue: Arc<LockDepMutex<VecDeque<ReadyItem>, EventHandlerReadyQueueLock>> =
1418                Default::default();
1419            let handler = EventHandler::Enqueue {
1420                key: KEY,
1421                queue: queue.clone(),
1422                sought_events: FdEvents::all(),
1423            };
1424            let waiter = Waiter::new();
1425            let wait_queue = TypedWaitQueue::<u64>::default();
1426
1427            let test_value = 100u64;
1428            let _wait_canceler =
1429                wait_queue.wait_async_value_with_handler(&waiter, test_value, handler);
1430
1431            assert!(queue.lock().is_empty());
1432
1433            // Notify wrong value
1434            wait_queue.notify_value(test_value + 1);
1435            assert!(queue.lock().is_empty());
1436
1437            // Notify right value
1438            wait_queue.notify_value(test_value);
1439
1440            waiter.wait(&current_task).expect("wait failed");
1441
1442            // Result delivered via POLLIN logic in central dispatcher
1443            let ready_items = queue.lock();
1444            assert_eq!(ready_items.len(), 1);
1445            assert!(ready_items[0].events.contains(FdEvents::POLLIN));
1446        })
1447        .await;
1448    }
1449}