Skip to main content

capsules_core/
driver_mutex.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2026.
4
5//! Queued, cooperative access to a shared kernel resource.
6//!
7//! This module provides [`DriverMutex`], a general purpose data structure for synchronizing access
8//! to shared resources within the Tock kernel's event loop.
9//!
10//! Terminology:
11//!
12//! * **resource**: An object wrapped by `DriverMutex`. Typically a chip-specific HIL driver.
13//! * **client**: A kernel object which depends on a shared resource and implements the
14//!   [`DriverMutexClient`] trait. Typically a capsule.
15//!
16//! `DriverMutex` sits between the resource and its clients and provides an API for clients to
17//! request exclusive access to the resource.
18//!
19//! ## Lifecycle
20//!
21//! 1. During board init, an instance is created and handed a reference to the wrapped resource.
22//! 2. Later during board init, client capsules which depend on the resource should be passed a
23//!    reference to the mutex wrapper.
24//!    * Within the each client's `Component::finalize()` implementation, the client is expected to
25//!      register with the mutex by calling [`DriverMutex::add_client()`]. The client must store the
26//!      resulting handle value; this is used later to request resource access.
27//! 4. At runtime, clients may call [`DriverMutex::request()`] to initiate access to the underlying
28//!    resource. The client is added to an internal queue.
29//! 5. When the resource becomes available, the mutex will invoke the client's
30//!    [`DriverMutexClient::ready()`] method, passing it an RAII guard which can be used to access
31//!    the resource.
32//! 6. When the client finishes interacting with the resource, it drops the RAII guard. This
33//!    automatically triggers the mutex to advance to the next client from its queue.
34//!
35//! ## Tradeoffs
36//!
37//! `DriverMutex` fills a very similar niche to the "virtualizer" pattern, but there are some
38//! important tradeoffs. In general, `DriverMutex` is more flexible but also more error prone.
39//!
40//! Some pitfalls to watch out for:
41//!
42//! * The mutex stores a shared reference to the underlying resource, so other objects may still be
43//!   able to access the resource without going through the mutex for synchronization.
44//! * Clients must be careful to retain the RAII guard until they are **completely finished** with
45//!   the underlying resource. This includes waiting for pending operations to complete. Dropping
46//!   the RAII guard too early can result in the resource being dispatched to the next queued
47//!   client while an operation is still in flight, leading to unexpected failures.
48//! * Each client may only have one pending request or active RAII guard at one time.
49//! * Requests are served to clients in FIFO order, but there is no timeout, forced release, or
50//!   recovery if a client retains or forgets its guard indefinitely. In other words, a misbehaving
51//!   client **can** starve all other clients of the resource.
52
53use core::any::Any;
54use core::cell::RefCell;
55use core::mem::{self, MaybeUninit};
56use core::ops::Deref;
57use core::ptr;
58
59use kernel::ErrorCode;
60use kernel::collections::queue::Queue;
61use kernel::collections::ring_buffer::RingBuffer;
62use kernel::deferred_call::{DeferredCall, DeferredCallClient};
63use kernel::utilities::cells::OptionalCell;
64
65/// Client interface for accessing resources wrapped in a [`DriverMutex`]
66///
67/// This trait must be implemented by any kernel object wishing to access a resource managed by a
68/// `DriverMutex`. The trait defines a single callback method `ready()` which will be invoked by the
69/// `DriverMutex` when the resource becomes available.
70///
71/// Note that this contract does not directly provide a [`DriverMutexRef`], but rather an instance
72/// of [`DriverMutexAny`]. It is the responsibility of the client to downcast the `DriverMutexAny`
73/// into the appropriate concrete type `T` before it can be used.
74///
75/// The reason for this extra indirection/reflection is to facilitate complex clients needing to
76/// interact with multiple `DriverMutex` instances. If we had made `DriverMutexClient` generic over
77/// `T`, then it would be practically impossible for such clients to `impl` the trait multiple times
78/// for each different `T` type, as doing so would cause Rust to complain about
79/// ambiguous/conflicting trait implementations.
80pub trait DriverMutexClient {
81    /// Called by the [`DriverMutex`] when the resource becomes available.
82    fn ready(&'static self, resource: DriverMutexAny);
83}
84
85/// Handle representing an individual client registration
86///
87/// Handles are used internally by [`DriverMutex`] to determine _which_ client is requesting access
88/// to the resource. A new, unique handle value is returned from each call to
89/// [`DriverMutex::add_client()`], and the client is expected to retain its handle so that it can be
90/// used later to request the resource.
91///
92/// A handle produced by one `DriverMutex` instance cannot be used with any other `DriverMutex`.
93/// Doing so will cause [`DriverMutex::request()`] to return [`ErrorCode::INVAL`].
94#[derive(Clone, Copy, PartialEq, Eq)]
95pub struct DriverMutexHandle {
96    /// Index of the client registration within the DriverMutex's client array
97    client_index: usize,
98
99    /// Raw pointer value of the DriverMutex in memory. Used to ensure handle values aren't confused
100    /// between different mutexes. Relies on each instance having a globally unique memory address.
101    mutex_ptr: *const (),
102}
103
104/// Internal state machine for a driver mutex
105enum State {
106    /// Resource is not in use
107    Free,
108
109    /// Resource is actively locked by a client
110    Locked {
111        /// Handle of the client which currently holds the lock
112        handle: DriverMutexHandle,
113    },
114}
115
116/// Internal bookkeeping for a driver mutex
117///
118/// This bookkeeping is the same regardless of the generic type `T` of the underlying resource,
119/// hence it does not need its own `T` parameter. This is important because it allows
120/// [`DriverMutexAny`] to contain a reference to the inner data and implement proper drop behavior.
121struct Inner {
122    /// Used to dispatch `ready()` callbacks on a separate stack frame
123    deferred_call: DeferredCall,
124
125    /// Queued client indices waiting for access
126    queue: RefCell<RingBuffer<'static, usize>>,
127
128    /// Current state of the mutex
129    state: RefCell<State>,
130}
131
132impl Inner {
133    /// Release the mutex when its guard is dropped and schedule the next queued client.
134    fn release(&self) {
135        self.state.replace(State::Free);
136        if self.queue.borrow().has_elements() {
137            self.deferred_call.set();
138        }
139    }
140}
141
142/// Specialized mutex used to guard HIL driver implementations
143///
144/// `DriverMutex` is a container type which wraps and provides mutual exclusion semantics for a HIL
145/// implementation within the Tock kernel. Even though Tock is fundamentally single-threaded, it is
146/// nevertheless highly concurrent and therefore susceptible to race conditions within its event
147/// loop when multiple kernel components are sharing the same underlying HIL driver.
148///
149/// ## Queuing
150///
151/// `DriverMutex` contains an integrated request queue. Multiple clients can
152/// [request][DriverMutex::request] access to the underlying resource, and they will be given access
153/// on a first-come first-served basis (as opposed to a traditional mutex, which would just return
154/// some "busy" error code).
155///
156/// The length of the internal queue is fixed, meaning it can only support a limited number of
157/// clients. Queue length is specified at construction time and may vary from instance to instance
158/// as needed.
159///
160/// ## RAII
161///
162/// Access to the underlying resource is mediated via [`DriverMutexAny`] and [`DriverMutexRef`].
163/// These are RAII guards which "release" the mutex upon being dropped. This provides some level of
164/// assurance at compile time that the underlying resource can only be accessed _while_ the mutex is
165/// held.
166///
167/// Each acquisition provides one guard. When that guard is dropped, the mutex is released. If
168/// another client is queued, a new RAII guard is passed to its
169/// [`ready()`][DriverMutexClient::ready] callback. This process is carried out within a
170/// [deferred call][DeferredCall] to avoid doing too much work directly within the RAII `drop()`
171/// method, which could otherwise lead to reentrancy hazards, poor performance, or overly deep call
172/// stacks.
173///
174/// A client may have either one queued request or one active guard per mutex. It must drop its
175/// guard before requesting that mutex again. Different mutexes may be acquired independently.
176pub struct DriverMutex<T: 'static> {
177    resource: &'static T,
178    inner: Inner,
179    clients: &'static [OptionalCell<&'static dyn DriverMutexClient>],
180}
181
182impl<T> DriverMutex<T> {
183    /// Creates a new `DriverMutex`.
184    pub fn new(
185        resource: &'static T,
186        clients: &'static [OptionalCell<&'static dyn DriverMutexClient>],
187        queue_buffer: &'static mut [MaybeUninit<usize>],
188    ) -> Self {
189        DriverMutex {
190            resource,
191            inner: Inner {
192                deferred_call: DeferredCall::new(),
193                queue: RefCell::new(RingBuffer::new(queue_buffer)),
194                state: RefCell::new(State::Free),
195            },
196            clients,
197        }
198    }
199
200    /// Registers a client with this `DriverMutex`.
201    ///
202    /// If the client was added successfully, a corresponding `DriverMutexHandle` is returned which
203    /// can be used later when calling `DriverMutex::request()`.
204    ///
205    /// To support more complex scenarios, the same client _may_ be added multiple times. In this
206    /// case, a new slot is _not_ consumed, and this function returns a copy of the handle that was
207    /// originally returned when the client was first added.
208    ///
209    /// `DriverMutex` supports only a fixed number of clients. If there is no more room for another
210    /// client, this method returns `None`.
211    pub fn add_client(
212        &'static self,
213        client: &'static dyn DriverMutexClient,
214    ) -> Option<DriverMutexHandle> {
215        for (i, slot) in self.clients.iter().enumerate() {
216            if let Some(c) = slot.get() {
217                // Check if the client in this slot matches the new incoming client
218                let is_same_client = ptr::eq(client, c);
219                if !is_same_client {
220                    // This is a different client, try the next slot
221                    continue;
222                }
223            } else {
224                // Empty slot, go ahead and claim it
225                slot.replace(client);
226            }
227
228            return Some(DriverMutexHandle {
229                client_index: i,
230                // N.B. The &self parameter has 'static lifetime, which guarantees this DriverMutex
231                //      will have a unique memory address for the duration of the program. That
232                //      allows us to use this pointer value to reliably detect handle confusion.
233                mutex_ptr: ptr::from_ref(self).cast(),
234            });
235        }
236
237        None
238    }
239
240    /// Requests access to the underlying resource.
241    ///
242    /// Client is added to the internal queue. When the resource becomes available, it will be
243    /// passed to the client's [`ready()`][DriverMutexClient::ready] callback. To avoid reentrancy
244    /// issues, this is guaranteed to happen in a separate Deferred Call.
245    ///
246    /// # Errors
247    ///
248    /// Returns [`ErrorCode::ALREADY`] if the client is already waiting in the queue or holds
249    /// the active guard.
250    ///
251    /// Returns [`ErrorCode::INVAL`] if passed a `handle` created from a different `DriverMutex`
252    /// instance.
253    ///
254    /// Returns [`ErrorCode::FAIL`] if the internal queue or state is already borrowed.
255    pub fn request(&self, handle: DriverMutexHandle) -> Result<(), ErrorCode> {
256        // Ensure the handle was created from this mutex instance
257        let self_ptr: *const () = ptr::from_ref(self).cast();
258        if self_ptr != handle.mutex_ptr {
259            return Err(ErrorCode::INVAL);
260        }
261
262        let mut queue = self
263            .inner
264            .queue
265            .try_borrow_mut()
266            .map_err(|_| ErrorCode::FAIL)?;
267
268        if queue.contains(handle.client_index) {
269            return Err(ErrorCode::ALREADY);
270        }
271
272        let state = self.inner.state.try_borrow().map_err(|_| ErrorCode::FAIL)?;
273
274        let should_schedule = match &*state {
275            State::Free => true,
276            State::Locked { handle: client } if *client == handle => {
277                return Err(ErrorCode::ALREADY);
278            }
279            State::Locked { .. } => false,
280        };
281
282        if !queue.enqueue(handle.client_index) {
283            // Queue length should match the component's client capacity, so this should be
284            // unreachable if handles are valid and duplicate requests are rejected.
285            return Err(ErrorCode::FAIL);
286        }
287
288        if should_schedule {
289            self.inner.deferred_call.set();
290        }
291
292        Ok(())
293    }
294}
295
296impl<T> DeferredCallClient for DriverMutex<T> {
297    fn handle_deferred_call(&'static self) {
298        let idx = match &mut *self.inner.state.borrow_mut() {
299            // Mutex is currently free
300            state @ State::Free => {
301                // Pop next client from the queue
302                let Some(client_index) = self.inner.queue.borrow_mut().dequeue() else {
303                    // Unexpected callback: queue is empty
304                    return;
305                };
306
307                // Mark mutex state as locked
308                let mutex_ptr = ptr::from_ref(self).cast();
309                *state = State::Locked {
310                    handle: DriverMutexHandle {
311                        client_index,
312                        mutex_ptr,
313                    },
314                };
315
316                // Dispatch ready callback to the newly popped client
317                client_index
318            }
319
320            State::Locked { .. } => return,
321        };
322
323        let resource_ref = DriverMutexAny {
324            resource: self.resource,
325            inner: &self.inner,
326        };
327
328        self.clients[idx].map(|c| {
329            c.ready(resource_ref);
330        });
331    }
332
333    fn register(&'static self) {
334        self.inner.deferred_call.register(self);
335    }
336}
337
338/// A type-erased reference to a resource guarded by a [`DriverMutex`]
339///
340/// See [`DriverMutexClient`] for an explanation of how/why `DriverMutexAny` should be used.
341pub struct DriverMutexAny {
342    resource: &'static dyn Any,
343    inner: &'static Inner,
344}
345
346impl DriverMutexAny {
347    /// Converts this guard to a guard for the concrete resource type `T`.
348    ///
349    /// On a type mismatch, returns the original guard without releasing the mutex.
350    pub fn downcast<T>(self) -> Result<DriverMutexRef<T>, Self> {
351        match self.resource.downcast_ref() {
352            Some(resource) => {
353                let new_ref = DriverMutexRef {
354                    resource,
355                    inner: self.inner,
356                };
357
358                // Transfer ownership to the typed guard without releasing the mutex.
359                mem::forget(self);
360
361                Ok(new_ref)
362            }
363
364            None => Err(self),
365        }
366    }
367}
368
369impl Drop for DriverMutexAny {
370    fn drop(&mut self) {
371        self.inner.release();
372    }
373}
374
375/// A smart pointer to a resource guarded by a [`DriverMutex`]
376pub struct DriverMutexRef<T: 'static> {
377    resource: &'static T,
378    inner: &'static Inner,
379}
380
381impl<T> Deref for DriverMutexRef<T> {
382    type Target = T;
383    fn deref(&self) -> &Self::Target {
384        self.resource
385    }
386}
387
388impl<T> Drop for DriverMutexRef<T> {
389    fn drop(&mut self) {
390        self.inner.release();
391    }
392}