Skip to main content

fdf_channel/
futures.rs

1// Copyright 2025 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
5//! Internal helpers for implementing futures against channel objects
6
7use std::mem::ManuallyDrop;
8use std::task::Waker;
9use zx::Status;
10
11use crate::channel::{Channel, try_read_raw};
12use crate::message::Message;
13use fdf_core::dispatcher::DriverDispatcherRef;
14use fdf_core::handle::DriverHandle;
15use fdf_sys::*;
16use libasync_dispatcher::OnDispatcher;
17
18use core::mem::MaybeUninit;
19use core::task::{Context, Poll};
20use fuchsia_sync::Mutex;
21use std::sync::Arc;
22
23pub use fdf_sys::fdf_handle_t;
24
25// state for a read message that is controlled by a lock
26#[derive(Default, Debug)]
27struct ReadMessageStateOpLocked {
28    /// the currently active waker for this read operation. Only set if there
29    /// is currently a pending read operation awaiting a callback.
30    waker: Option<Waker>,
31    /// if the channel was dropped while a pending callback was active, so the
32    /// callback should close the driverhandle when it fires.
33    channel_dropped: bool,
34    /// whether cancelation of this future will happen asynchronously through
35    /// the callback or immediately when [`fdf_channel_cancel_wait`] is called.
36    /// This is used to decide what's responsible for freeing the reference
37    /// to this object when the future is canceled.
38    cancelation_is_async: bool,
39}
40
41/// This struct is shared between the future and the driver runtime, with the first field
42/// being managed by the driver runtime and the second by the future. It will be held by two
43/// [`Arc`]s, one for each of the future and the runtime.
44///
45/// The future's [`Arc`] will be dropped when the future is either fulfilled or cancelled through
46/// normal [`Drop`] of the future.
47///
48/// The runtime's [`Arc`]'s dropping varies depending on whether the dispatcher it was registered on
49/// was synchronized or not, and whether it was cancelled or not. The callback will only ever be
50/// called *up to* one time.
51///
52/// If the dispatcher is synchronized, then the callback will *only* be called on fulfillment of the
53/// read wait.
54#[repr(C)]
55#[derive(Debug)]
56pub(crate) struct ReadMessageStateOp {
57    /// This must be at the start of the struct so that `ReadMessageStateOp` can be cast to and from `fdf_channel_read`.
58    read_op: fdf_channel_read,
59    state: Mutex<ReadMessageStateOpLocked>,
60}
61
62impl ReadMessageStateOp {
63    unsafe extern "C" fn handler(
64        _dispatcher: *mut fdf_dispatcher,
65        read_op: *mut fdf_channel_read,
66        _status: i32,
67    ) {
68        // Note: we don't really do anything different based on whether the callback
69        // says canceled. If the future was canceled by being dropped, it won't poll
70        // again since it was dropped.
71        // The only unusual case is when the dispatcher is shutting down, and in that
72        // case we will wake the future and it will try to read and get a more useful
73        // error.
74        // Meanwhile, since we use the same state object across multiple
75        // futures due to needing to handle async cancelation, trying to track the
76        // underlying reason for the cancelation becomes more tricky than it's worth.
77
78        // SAFETY: When setting up the read op, we incremented the refcount of the `Arc` to allow
79        // for this handler to reconstitute it.
80        let op: Arc<Self> = unsafe { Arc::from_raw(read_op.cast()) };
81
82        let mut state = op.state.lock();
83        if state.channel_dropped {
84            // SAFETY: since the channel dropped we are the only outstanding owner of the
85            // channel object.
86            unsafe { fdf_handle_close(op.read_op.channel) };
87        }
88        let Some(waker) = state.waker.take() else {
89            // the waker was already taken, presumably because the future was dropped.
90            return;
91        };
92        // make sure to drop the lock before calling the waker.
93        drop(state);
94        waker.wake()
95    }
96
97    /// Called by the channel on drop to indicate that the channel has been dropped and
98    /// find out whether it needs to defer dropping the handle until the callback is called.
99    pub fn set_channel_dropped(&self) -> bool {
100        let mut state = self.state.lock();
101        if state.waker.is_some() {
102            state.channel_dropped = true;
103            false
104        } else {
105            true
106        }
107    }
108}
109
110/// An object for managing the state of an async channel read message operation that can be used to
111/// implement futures.
112pub struct ReadMessageState {
113    op: Arc<ReadMessageStateOp>,
114    channel: ManuallyDrop<DriverHandle>,
115}
116
117impl ReadMessageState {
118    /// Creates a new raw read message state that can be used to implement a [`Future`] that reads
119    /// data from a channel and then converts it to the appropriate type. It also allows for
120    /// different ways of storing and managing the dispatcher we wait on by deferring the
121    /// dispatcher used to poll time. This state is registered with the given [`Channel`]
122    /// so that dropping the channel will correctly free resources.
123    ///
124    /// # Safety
125    ///
126    /// The caller is responsible for ensuring that the handle inside `channel` outlives this
127    /// object.
128    pub unsafe fn register_read_wait<T: ?Sized>(channel: &mut Channel<T>) -> Self {
129        // SAFETY: The caller is responsible for ensuring that the handle is a correct channel handle
130        // and that the handle will outlive the created [`ReadMessageState`].
131        let channel_handle = unsafe { channel.handle.get_raw() };
132        let op = channel
133            .wait_state
134            .get_or_insert_with(|| {
135                Arc::new(ReadMessageStateOp {
136                    read_op: fdf_channel_read {
137                        channel: channel_handle.get(),
138                        handler: Some(ReadMessageStateOp::handler),
139                        ..Default::default()
140                    },
141                    state: Mutex::new(ReadMessageStateOpLocked::default()),
142                })
143            })
144            .clone();
145        Self {
146            op,
147            // SAFETY: We know this is a valid driver handle by construction and we are
148            // storing this handle in a [`ManuallyDrop`] to prevent it from being double-dropped.
149            // The caller is responsible for ensuring that the handle outlives this object.
150            channel: ManuallyDrop::new(unsafe { DriverHandle::new_unchecked(channel_handle) }),
151        }
152    }
153
154    /// Polls this channel read operation against the given dispatcher.
155    #[expect(clippy::type_complexity)]
156    pub fn poll_with_dispatcher<D: OnDispatcher>(
157        &mut self,
158        cx: &mut Context<'_>,
159        dispatcher: D,
160    ) -> Poll<Result<Option<Message<[MaybeUninit<u8>]>>, Status>> {
161        let mut state = self.op.state.lock();
162
163        match try_read_raw(&self.channel) {
164            Ok(res) => Poll::Ready(Ok(res)),
165            Err(Status::SHOULD_WAIT) => {
166                // if we haven't yet set a waker, that means we haven't started the wait operation
167                // yet.
168                if state.waker.is_none() {
169                    // increment the reference count of the read op to account for the copy that will be given to
170                    // `fdf_channel_wait_async`.
171                    let op = Arc::into_raw(self.op.clone());
172                    let res = dispatcher.on_maybe_dispatcher(|dispatcher| {
173                        let dispatcher = DriverDispatcherRef::from_async_dispatcher(dispatcher);
174                        // if we're not running on the same dispatcher as we're waiting from, we
175                        // want to force async cancellation
176                        let options = if !dispatcher.is_current_dispatcher() {
177                            FDF_CHANNEL_WAIT_OPTION_FORCE_ASYNC_CANCEL
178                        } else {
179                            0
180                        };
181                        // SAFETY: the `ReadMessageStateOp` starts with an `fdf_channel_read` struct and
182                        // has `repr(C)` layout, so is safe to be cast to the latter.
183                        let res = Status::ok(unsafe {
184                            fdf_channel_wait_async(
185                                fdf_core::dispatcher_ptr(&dispatcher).as_ptr(),
186                                op.cast_mut().cast(),
187                                options,
188                            )
189                        });
190                        if res.is_ok() {
191                            // only replace the waker if we succeeded, so we'll try again next time
192                            // otherwise.
193                            state.waker.replace(cx.waker().clone());
194                        } else {
195                            // reconstitute the arc we made for the callback so it can be dropped
196                            // since the async wait didn't succeed.
197                            drop(unsafe { Arc::from_raw(op) });
198                        }
199                        // if the dispatcher we're waiting on is unsynchronized, the callback
200                        // will drop the Arc and we need to indicate to our own Drop impl
201                        // that it should not.
202                        res.map(|_| {
203                            options == FDF_CHANNEL_WAIT_OPTION_FORCE_ASYNC_CANCEL
204                                || dispatcher.is_unsynchronized()
205                        })
206                    });
207
208                    // the default state should be that `drop` will free the arc.
209                    state.cancelation_is_async = false;
210                    match res {
211                        Err(Status::BAD_STATE) => {
212                            return Poll::Pending; // a pending await is being cancelled
213                        }
214                        Ok(cancelation_is_async) => {
215                            state.cancelation_is_async = cancelation_is_async;
216                        }
217                        Err(e) => return Poll::Ready(Err(e)),
218                    }
219                }
220                Poll::Pending
221            }
222            Err(e) => Poll::Ready(Err(e)),
223        }
224    }
225}
226
227impl Drop for ReadMessageState {
228    fn drop(&mut self) {
229        let mut state = self.op.state.lock();
230        if state.waker.is_none() {
231            // if there's no waker either the callback has already fired or we never waited on this
232            // future in the first place, so just leave it be.
233            return;
234        }
235
236        // SAFETY: since we hold a lifetimed-reference to the channel object here, the channel must
237        // be valid.
238        let res = Status::ok(unsafe { fdf_channel_cancel_wait(self.channel.get_raw().get()) });
239        match res {
240            Ok(_) => {}
241            Err(Status::NOT_FOUND) => {
242                // the callback is already being called or the wait was already cancelled, so just
243                // return and leave it.
244                return;
245            }
246            Err(e) => panic!("Unexpected error {e:?} cancelling driver channel read wait"),
247        }
248        // SAFETY: if the channel was waited on by a synchronized dispatcher, and the cancel was
249        // successful, the callback will not be called and we will have to free the `Arc` that the
250        // callback would have consumed.
251        if !state.cancelation_is_async {
252            // steal the waker so it doesn't get called, if there is one.
253            state.waker.take();
254            unsafe { Arc::decrement_strong_count(Arc::as_ptr(&self.op)) };
255        }
256    }
257}
258
259#[cfg(test)]
260mod test {
261    use std::pin::pin;
262    use std::sync::Weak;
263
264    use fdf_core::dispatcher::CurrentDispatcher;
265    use fdf_env::test::{spawn_in_driver, spawn_in_driver_etc};
266    use libasync_dispatcher::OnDispatcher;
267
268    use crate::arena::Arena;
269    use crate::channel::{Channel, read_raw};
270
271    use super::*;
272
273    /// assert that the strong count of an arc is correct
274    #[track_caller]
275    fn assert_strong_count<T>(arc: &Weak<T>, count: usize) {
276        assert_eq!(Weak::strong_count(arc), count, "unexpected strong count on arc");
277    }
278
279    /// create, poll, and then immediately drop a read future for a channel and verify
280    /// that the internal op arc has the right refcount at all steps. Returns a copy
281    /// of the op arc at the end so it can be verified that the count goes down
282    /// to zero correctly.
283    async fn read_and_drop<T: ?Sized + 'static, D: OnDispatcher + Unpin>(
284        channel: &mut Channel<T>,
285        dispatcher: D,
286    ) -> Weak<ReadMessageStateOp> {
287        let fut = unsafe { read_raw(channel, dispatcher) };
288        let op_arc = Arc::downgrade(&fut.raw_fut.op);
289        assert_strong_count(&op_arc, 2);
290        let mut fut = pin!(fut);
291        let Poll::Pending = futures::poll!(fut.as_mut()) else {
292            panic!("expected pending state after polling channel read once");
293        };
294        assert_strong_count(&op_arc, 3);
295        op_arc
296    }
297
298    #[test]
299    fn early_cancel_future() {
300        spawn_in_driver("early cancellation", async {
301            let (mut a, b) = Channel::create();
302
303            // create, poll, and then immediately drop a read future for channel `a`
304            // so that it properly sets up the wait.
305            read_and_drop(&mut a, CurrentDispatcher).await;
306            b.write_with_data(Arena::new(), |arena| arena.insert(1)).unwrap();
307            assert_eq!(a.read(CurrentDispatcher).await.unwrap().unwrap().data(), Some(&1));
308        })
309    }
310
311    #[test]
312    fn very_early_cancel_state_drops_correctly() {
313        spawn_in_driver("early cancellation drop correctness", async {
314            let (mut a, _b) = Channel::<[u8]>::create();
315
316            // drop before even polling it should drop the arc correctly
317            let fut = unsafe { read_raw(&mut a, CurrentDispatcher) };
318            let op_arc = Arc::downgrade(&fut.raw_fut.op);
319            assert_strong_count(&op_arc, 2);
320            drop(fut);
321            assert_strong_count(&op_arc, 1);
322        })
323    }
324
325    #[test]
326    fn synchronized_early_cancel_state_drops_correctly() {
327        spawn_in_driver("early cancellation drop correctness", async {
328            let (mut a, _b) = Channel::<[u8]>::create();
329
330            assert_strong_count(&read_and_drop(&mut a, CurrentDispatcher).await, 1);
331        });
332    }
333
334    #[test]
335    fn unsynchronized_early_cancel_state_drops_correctly() {
336        // the channel needs to outlive the dispatcher for this test because the channel shouldn't
337        // be closed before the read wait has been cancelled.
338        let (mut a, _b) = Channel::<[u8]>::create();
339        let unsync_op =
340            spawn_in_driver_etc("early cancellation drop correctness", false, true, async move {
341                // We send the arc out to be checked after the dispatcher has shut down so
342                // that we can be sure that the callback has had a chance to be called.
343                // We send the channel back out so that it lives long enough for the
344                // cancellation to be called on it.
345                read_and_drop(&mut a, CurrentDispatcher).await
346            });
347
348        // check that there are no more owners of the inner op for the unsynchronized dispatcher.
349        assert_strong_count(&unsync_op, 0);
350    }
351
352    #[test]
353    fn unsynchronized_early_cancel_state_drops_repeatedly_correctly() {
354        // the channel needs to outlive the dispatcher for this test because the channel shouldn't
355        // be closed before the read wait has been cancelled.
356        let (mut a, _b) = Channel::<[u8]>::create();
357        spawn_in_driver_etc("early cancellation drop correctness", false, true, async move {
358            for _ in 0..10000 {
359                let mut fut = unsafe { read_raw(&mut a, CurrentDispatcher) };
360                let Poll::Pending = futures::poll!(&mut fut) else {
361                    panic!("expected pending state after polling channel read once");
362                };
363                drop(fut);
364            }
365        });
366    }
367}