fdf_env/
lib.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//! Safe bindings for driver runtime environment.
6
7#![deny(missing_docs)]
8
9use fdf_sys::*;
10
11use core::ffi;
12use core::marker::PhantomData;
13use core::ptr::{null_mut, NonNull};
14
15use zx::Status;
16
17use fdf::{Dispatcher, DispatcherBuilder, DispatcherRef, ShutdownObserver};
18
19pub mod test;
20
21/// Create the dispatcher as configured by this object. This must be called from a
22/// thread managed by the driver runtime. The dispatcher returned is owned by the caller,
23/// and will initiate asynchronous shutdown when the object is dropped unless
24/// [`Dispatcher::release`] is called on it to convert it into an unowned [`DispatcherRef`].
25///
26fn create_with_driver<'a>(
27    dispatcher: DispatcherBuilder,
28    driver: DriverRefTypeErased<'a>,
29) -> Result<Dispatcher, Status> {
30    let mut out_dispatcher = null_mut();
31    let owner = driver.0;
32    let options = dispatcher.options;
33    let name = dispatcher.name.as_ptr() as *mut ffi::c_char;
34    let name_len = dispatcher.name.len();
35    let scheduler_role = dispatcher.scheduler_role.as_ptr() as *mut ffi::c_char;
36    let scheduler_role_len = dispatcher.scheduler_role.len();
37    let observer =
38        dispatcher.shutdown_observer.unwrap_or_else(|| ShutdownObserver::new(|_| {})).into_ptr();
39    // SAFETY: all arguments point to memory that will be available for the duration
40    // of the call, except `observer`, which will be available until it is unallocated
41    // by the dispatcher exit handler.
42    Status::ok(unsafe {
43        fdf_env_dispatcher_create_with_owner(
44            owner,
45            options,
46            name,
47            name_len,
48            scheduler_role,
49            scheduler_role_len,
50            observer,
51            &mut out_dispatcher,
52        )
53    })?;
54    // SAFETY: `out_dispatcher` is valid by construction if `fdf_dispatcher_create` returns
55    // ZX_OK.
56    Ok(unsafe { Dispatcher::from_raw(NonNull::new_unchecked(out_dispatcher)) })
57}
58
59/// As with [`create_with_driver`], this creates a new dispatcher as configured by this object, but
60/// instead of returning an owned reference it immediately releases the reference to be
61/// managed by the driver runtime.
62///
63/// # Safety
64///
65/// |owner| must outlive the dispatcher. You can use the shutdown_observer to find out when it is
66/// safe to drop it.
67fn create_with_driver_released<'a>(
68    dispatcher: DispatcherBuilder,
69    driver: DriverRefTypeErased<'a>,
70) -> Result<DispatcherRef<'static>, Status> {
71    create_with_driver(dispatcher, driver).map(Dispatcher::release)
72}
73
74/// A marker trait for a function that can be used as a driver shutdown observer with
75/// [`Driver::shutdown`].
76pub trait DriverShutdownObserverFn<T: 'static>:
77    FnOnce(DriverRef<'static, T>) + Send + Sync + 'static
78{
79}
80impl<T, U: 'static> DriverShutdownObserverFn<U> for T where
81    T: FnOnce(DriverRef<'static, U>) + Send + Sync + 'static
82{
83}
84
85/// A shutdown observer for [`fdf_dispatcher_create`] that can call any kind of callback instead of
86/// just a C-compatible function when a dispatcher is shutdown.
87///
88/// # Safety
89///
90/// This object relies on a specific layout to allow it to be cast between a
91/// `*mut fdf_dispatcher_shutdown_observer` and a `*mut ShutdownObserver`. To that end,
92/// it is important that this struct stay both `#[repr(C)]` and that `observer` be its first member.
93#[repr(C)]
94struct DriverShutdownObserver<T: 'static> {
95    observer: fdf_env_driver_shutdown_observer,
96    shutdown_fn: Box<dyn DriverShutdownObserverFn<T>>,
97    driver: Driver<T>,
98}
99
100impl<T: 'static> DriverShutdownObserver<T> {
101    /// Creates a new [`ShutdownObserver`] with `f` as the callback to run when a dispatcher
102    /// finishes shutting down.
103    fn new<F: DriverShutdownObserverFn<T>>(driver: Driver<T>, f: F) -> Self {
104        let shutdown_fn = Box::new(f);
105        Self {
106            observer: fdf_env_driver_shutdown_observer { handler: Some(Self::handler) },
107            shutdown_fn,
108            driver,
109        }
110    }
111
112    /// Begins the driver shutdown procedure.
113    /// Turns this object into a stable pointer suitable for passing to
114    /// [`fdf_env_shutdown_dispatchers_async`] by wrapping it in a [`Box`] and leaking it
115    /// to be reconstituded by [`Self::handler`] when the dispatcher is shut down.
116    fn begin(self) -> Result<(), Status> {
117        let driver = self.driver.inner.as_ptr() as *const _;
118        // Note: this relies on the assumption that `self.observer` is at the beginning of the
119        // struct.
120        let this = Box::into_raw(Box::new(self)) as *mut _;
121        // SAFTEY: driver is owned by the driver framework and will be kept alive until the handler
122        // callback is triggered
123        if let Err(e) = Status::ok(unsafe { fdf_env_shutdown_dispatchers_async(driver, this) }) {
124            // SAFTEY: The framework didn't actually take ownership of the object if the call
125            // fails, so we can recover it to avoid leaking.
126            let _ = unsafe { Box::from_raw(this as *mut DriverShutdownObserver<T>) };
127            return Err(e);
128        }
129        Ok(())
130    }
131
132    /// The callback that is registered with the driver that will be called when the driver
133    /// is shut down.
134    ///
135    /// # Safety
136    ///
137    /// This function should only ever be called by the driver runtime at dispatcher shutdown
138    /// time, must only ever be called once for any given [`ShutdownObserver`] object, and
139    /// that [`ShutdownObserver`] object must have previously been made into a pointer by
140    /// [`Self::into_ptr`].
141    unsafe extern "C" fn handler(
142        driver: *const ffi::c_void,
143        observer: *mut fdf_env_driver_shutdown_observer_t,
144    ) {
145        // SAFETY: The driver framework promises to only call this function once, so we can
146        // safely take ownership of the [`Box`] and deallocate it when this function ends.
147        let observer = unsafe { Box::from_raw(observer as *mut DriverShutdownObserver<T>) };
148        (observer.shutdown_fn)(DriverRef(driver as *const T, PhantomData));
149    }
150}
151
152/// An owned handle to a Driver instance that can be used to create initial dispatchers.
153#[derive(Debug)]
154pub struct Driver<T> {
155    pub(crate) inner: NonNull<T>,
156    shutdown_triggered: bool,
157}
158
159/// An unowned handle to the driver that is returned through certain environment APIs like
160/// |get_driver_on_thread_koid|.
161pub struct UnownedDriver {
162    inner: *const ffi::c_void,
163}
164
165/// SAFETY: This inner pointer is movable across threads.
166unsafe impl<T: Send> Send for Driver<T> {}
167
168impl<T: 'static> Driver<T> {
169    /// Returns a builder capable of creating a new dispatcher. Note that this dispatcher cannot
170    /// outlive the driver and is only capable of being stopped by shutting down the driver. It is
171    /// meant to be created to serve as the initial or default dispatcher for a driver.
172    pub fn new_dispatcher(
173        &self,
174        dispatcher: DispatcherBuilder,
175    ) -> Result<DispatcherRef<'static>, Status> {
176        create_with_driver_released(dispatcher, self.as_ref_type_erased())
177    }
178
179    /// Run a closure in the context of a driver.
180    pub fn enter<R>(&mut self, f: impl FnOnce() -> R) -> R {
181        unsafe { fdf_env_register_driver_entry(self.inner.as_ptr() as *const _) };
182        let res = f();
183        unsafe { fdf_env_register_driver_exit() };
184        res
185    }
186
187    /// Adds an allowed scheduler role to the driver
188    pub fn add_allowed_scheduler_role(&self, scheduler_role: &str) {
189        let driver_ptr = self.inner.as_ptr() as *const _;
190        let scheduler_role_ptr = scheduler_role.as_ptr() as *mut ffi::c_char;
191        let scheduler_role_len = scheduler_role.len();
192        unsafe {
193            fdf_env_add_allowed_scheduler_role_for_driver(
194                driver_ptr,
195                scheduler_role_ptr,
196                scheduler_role_len,
197            )
198        };
199    }
200
201    /// Asynchronously shuts down all dispatchers owned by |driver|.
202    /// |f| will be called once shutdown completes. This is guaranteed to be
203    /// after all the dispatcher's shutdown observers have been called, and will be running
204    /// on the thread of the final dispatcher which has been shutdown.
205    pub fn shutdown<F: DriverShutdownObserverFn<T>>(mut self, f: F) {
206        self.shutdown_triggered = true;
207        // It should be impossible for this to fail as we ensure we are the only caller of this
208        // API, so it cannot be triggered twice nor before the driver has been registered with the
209        // framework.
210        DriverShutdownObserver::new(self, f)
211            .begin()
212            .expect("Unexpectedly failed start shutdown procedure")
213    }
214
215    /// Create a reference to a driver without ownership. The returned reference lacks the ability
216    /// to perform most actions available to the owner of the driver, therefore it doesn't need to
217    /// have it's lifetime tracked closely.
218    fn as_ref_type_erased<'a>(&'a self) -> DriverRefTypeErased<'a> {
219        DriverRefTypeErased(self.inner.as_ptr() as *const _, PhantomData)
220    }
221
222    /// Releases ownership of this driver instance, allowing it to be shut down when the runtime
223    /// shuts down.
224    pub fn release(self) -> DriverRef<'static, T> {
225        DriverRef(self.inner.as_ptr() as *const _, PhantomData)
226    }
227}
228
229impl<T> Drop for Driver<T> {
230    fn drop(&mut self) {
231        assert!(self.shutdown_triggered, "Cannot drop driver, must call shutdown method instead");
232    }
233}
234
235impl<T> PartialEq<UnownedDriver> for Driver<T> {
236    fn eq(&self, other: &UnownedDriver) -> bool {
237        return self.inner.as_ptr() as *const _ == other.inner;
238    }
239}
240
241// Note that inner type is not guaranteed to not be null.
242#[derive(Clone, Copy, PartialEq)]
243struct DriverRefTypeErased<'a>(*const ffi::c_void, PhantomData<&'a u32>);
244
245impl Default for DriverRefTypeErased<'_> {
246    fn default() -> Self {
247        DriverRefTypeErased(std::ptr::null(), PhantomData)
248    }
249}
250
251/// A lifetime-bound reference to a driver handle.
252pub struct DriverRef<'a, T>(pub *const T, PhantomData<&'a Driver<T>>);
253
254/// The driver runtime environment
255pub struct Environment;
256
257impl Environment {
258    /// Whether the environment should enforce scheduler roles. Used with [`Self::start`].
259    pub const ENFORCE_ALLOWED_SCHEDULER_ROLES: u32 = 1;
260    /// Whether the environment should dynamically spawn threads on-demand for sync call dispatchers.
261    /// Used with [`Self::start`].
262    pub const DYNAMIC_THREAD_SPAWNING: u32 = 2;
263
264    /// Start the driver runtime. This sets up the initial thread that the dispatchers run on.
265    pub fn start(options: u32) -> Result<Environment, Status> {
266        // SAFETY: calling fdf_env_start, which does not have any soundness
267        // concerns for rust code. It may be called multiple times without any problems.
268        Status::ok(unsafe { fdf_env_start(options) })?;
269        Ok(Self)
270    }
271
272    /// Creates a new driver. It is expected that the driver passed in is a leaked pointer which
273    /// will only be recovered by triggering the shutdown method on the driver.
274    ///
275    /// # Panics
276    ///
277    /// This method will panic if |driver| is not null.
278    pub fn new_driver<T>(&self, driver: *const T) -> Driver<T> {
279        // We cast to *mut because there is not equivlaent version of NonNull for *const T.
280        Driver {
281            inner: NonNull::new(driver as *mut _).expect("driver must not be null"),
282            shutdown_triggered: false,
283        }
284    }
285
286    // TODO: Consider tracking all drivers and providing a method to shutdown all outstanding
287    // drivers and block until they've all finished shutting down.
288
289    /// Returns whether the current thread is managed by the driver runtime or not.
290    fn current_thread_managed_by_driver_runtime() -> bool {
291        // Safety: Calling fdf_dispatcher_get_current_dispatcher from any thread is safe. Because
292        // we are not actually using the dispatcher, we don't need to worry about it's lifetime.
293        !unsafe { fdf_dispatcher_get_current_dispatcher().is_null() }
294    }
295
296    /// Resets the driver runtime to zero threads. This may only be called when there are no
297    /// existing dispatchers.
298    ///
299    /// # Panics
300    ///
301    /// This method should not be called from a thread managed by the driver runtime,
302    /// such as from tasks or ChannelRead callbacks.
303    pub fn reset(&self) {
304        assert!(
305            Self::current_thread_managed_by_driver_runtime() == false,
306            "reset must be called from a thread not managed by the driver runtime"
307        );
308        // SAFETY: calling fdf_env_reset, which does not have any soundness
309        // concerns for rust code. It may be called multiple times without any problems.
310        unsafe { fdf_env_reset() };
311    }
312
313    /// Destroys all dispatchers in the process and blocks the current thread
314    /// until each runtime dispatcher in the process is observed to have been destroyed.
315    ///
316    /// This should only be used called after all drivers have been shutdown.
317    ///
318    /// # Panics
319    ///
320    /// This method should not be called from a thread managed by the driver runtime,
321    /// such as from tasks or ChannelRead callbacks.
322    pub fn destroy_all_dispatchers(&self) {
323        assert!(Self::current_thread_managed_by_driver_runtime() == false,
324            "destroy_all_dispatchers must be called from a thread not managed by the driver runtime");
325        unsafe { fdf_env_destroy_all_dispatchers() };
326    }
327
328    /// Returns whether the dispatcher has any queued tasks.
329    pub fn dispatcher_has_queued_tasks(&self, dispatcher: DispatcherRef<'_>) -> bool {
330        unsafe { fdf_env_dispatcher_has_queued_tasks(dispatcher.inner().as_ptr()) }
331    }
332
333    /// Returns the current maximum number of threads which will be spawned for thread pool associated
334    /// with the given scheduler role.
335    ///
336    /// |scheduler_role| is the name of the role which is passed when creating dispatchers.
337    pub fn get_thread_limit(&self, scheduler_role: &str) -> u32 {
338        let scheduler_role_ptr = scheduler_role.as_ptr() as *mut ffi::c_char;
339        let scheduler_role_len = scheduler_role.len();
340        unsafe { fdf_env_get_thread_limit(scheduler_role_ptr, scheduler_role_len) }
341    }
342
343    /// Sets the number of threads which will be spawned for thread pool associated with the given
344    /// scheduler role. It cannot shrink the limit less to a value lower than the current number of
345    /// threads in the thread pool.
346    ///
347    /// |scheduler_role| is the name of the role which is passed when creating dispatchers.
348    /// |max_threads| is the number of threads to use as new limit.
349    pub fn set_thread_limit(&self, scheduler_role: &str, max_threads: u32) -> Result<(), Status> {
350        let scheduler_role_ptr = scheduler_role.as_ptr() as *mut ffi::c_char;
351        let scheduler_role_len = scheduler_role.len();
352        Status::ok(unsafe {
353            fdf_env_set_thread_limit(scheduler_role_ptr, scheduler_role_len, max_threads)
354        })
355    }
356
357    /// Gets the driver currently running on the thread identified by |thread_koid|, if the thread
358    /// is running on this driver host with a driver.
359    pub fn get_driver_on_thread_koid(&self, thread_koid: zx::Koid) -> Option<UnownedDriver> {
360        let mut driver = std::ptr::null();
361        unsafe {
362            Status::ok(fdf_env_get_driver_on_tid(thread_koid.raw_koid(), &mut driver)).ok()?;
363        }
364        if driver.is_null() {
365            None
366        } else {
367            Some(UnownedDriver { inner: driver })
368        }
369    }
370}