Skip to main content

kernel/
deferred_call.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 2022.
4
5//! Hardware-independent kernel interface for deferred calls.
6//!
7//! This allows any struct in the kernel which implements [`DeferredCallClient`]
8//! to set and receive deferred calls, Tock's version of software interrupts.
9//!
10//! These can be used to implement long-running in-kernel algorithms or software
11//! devices that are supposed to work like hardware devices. Essentially, this
12//! allows the chip to handle more important interrupts, and lets a kernel
13//! component return the function call stack up to the scheduler, automatically
14//! being called again.
15//!
16//! Initialization
17//! --------------
18//!
19//! Before any [`DeferredCall`]s are created, the internal state used by the
20//! implementation must be initialized. Boards must initialize deferred calls
21//! by calling either `initialize_deferred_call_state` or
22//! [`initialize_deferred_call_state_unsafe`]. Depending on the hardware state
23//! available (i.e., atomic support), boards will only have one initialization
24//! routine available.
25//!
26//! On boards that must use the unsafe version
27//! ([`initialize_deferred_call_state_unsafe`]), they must be careful to only
28//! call [`initialize_deferred_call_state_unsafe`] once from the main execution
29//! thread to meet the safety requirements.
30//!
31//! Usage
32//! -----
33//!
34//! The `DEFCALLS` array size determines how many [`DeferredCall`]s may be
35//! registered. By default this is set to 32. To support more deferred calls,
36//! this file would need to be modified to use a larger variable for `BITMASK`
37//! (e.g. `BITMASK` could be a u64 and the array size increased to 64). If more
38//! than 32 deferred calls are created, the kernel will panic at the beginning
39//! of the kernel loop.
40//!
41//! ```rust
42//! use kernel::deferred_call::{DeferredCall, DeferredCallClient};
43//! use kernel::static_init;
44//!
45//! // Don't use this! Use the actual `ThreadIdProvider` from your arch crate.
46//! struct DummyThreadIdProvider {}
47//! unsafe impl kernel::platform::chip::ThreadIdProvider for DummyThreadIdProvider {
48//!     fn running_thread_id() -> usize { 0 }
49//! }
50//!
51//! // Initialize the deferred call mechanism.
52//! #[cfg(target_has_atomic = "ptr")]
53//! kernel::deferred_call::initialize_deferred_call_state::<DummyThreadIdProvider>();
54//! #[cfg(not(target_has_atomic = "ptr"))]
55//! unsafe { kernel::deferred_call::initialize_deferred_call_state_unsafe::<DummyThreadIdProvider>(); }
56//!
57//!
58//! struct SomeCapsule {
59//!     deferred_call: DeferredCall
60//! }
61//! impl SomeCapsule {
62//!     pub fn new() -> Self {
63//!         Self {
64//!             deferred_call: DeferredCall::new(),
65//!         }
66//!     }
67//! }
68//! impl DeferredCallClient for SomeCapsule {
69//!     fn handle_deferred_call(&self) {
70//!         // Your action here
71//!     }
72//!
73//!     fn register(&'static self) {
74//!         self.deferred_call.register(self);
75//!     }
76//! }
77//!
78//! // main.rs or your component must register the capsule with its deferred
79//! // call. This should look like:
80//! let some_capsule = unsafe { static_init!(SomeCapsule, SomeCapsule::new()) };
81//! some_capsule.register();
82//! ```
83
84use crate::platform::chip::ThreadIdProvider;
85use crate::utilities::cells::OptionalCell;
86use crate::utilities::single_thread_value::SingleThreadValue;
87use core::cell::Cell;
88use core::marker::Copy;
89use core::marker::PhantomData;
90
91/// This trait should be implemented by clients which need to receive
92/// [`DeferredCall`]s.
93// This trait is not intended to be used as a trait object; e.g. you should not
94// create a `&dyn DeferredCallClient`. The `Sized` supertrait prevents this.
95pub trait DeferredCallClient: Sized {
96    /// Software interrupt function that is called when the deferred call is
97    /// triggered.
98    fn handle_deferred_call(&self);
99
100    // This function should be implemented as
101    // `self.deferred_call.register(&self);`.
102    fn register(&'static self);
103}
104
105/// This struct serves as a lightweight alternative to the use of trait objects
106/// (e.g. `&dyn DeferredCall`).
107///
108/// Using a trait object will include a 20 byte vtable per instance, but this
109/// alternative stores only the data and function pointers, 8 bytes per
110/// instance.
111#[derive(Copy, Clone)]
112struct DynDefCallRef<'a> {
113    data: *const (),
114    callback: fn(*const ()),
115    _lifetime: PhantomData<&'a ()>,
116}
117
118impl<'a> DynDefCallRef<'a> {
119    fn new<T: DeferredCallClient>(x: &'a T) -> Self {
120        let data: *const () = core::ptr::from_ref(x).cast();
121        Self {
122            data,
123            callback: |p| {
124                // SAFETY: We define the callback function as being a closure which casts
125                // the passed pointer to be the appropriate type (a pointer to `T`) and then
126                // calls `T::handle_deferred_call()`. In practice, the closure is optimized
127                // away by LLVM when the ABI of the closure and the underlying function are
128                // identical, making this zero-cost, but saving us from having to trust that
129                // `fn(*const ())` and `fn handle_deferred_call(&self)` will always have the
130                // same calling convention for any type.
131                unsafe { T::handle_deferred_call(&*p.cast()) }
132            },
133            _lifetime: PhantomData,
134        }
135    }
136}
137
138impl DynDefCallRef<'_> {
139    // More efficient to pass by `self` if we don't have to implement
140    // `DeferredCallClient` directly.
141    fn handle_deferred_call(self) {
142        (self.callback)(self.data)
143    }
144}
145
146/// Counter for the number of deferred calls that have been created, this is
147/// used to track that no more than 32 deferred calls have been created.
148// All 3 of the below global statics are accessed only in this file, and all
149// accesses are via immutable references. Tock is single threaded, so each will
150// only ever be accessed via an immutable reference from the single kernel
151// thread. TODO: Once Tock decides on an approach to replace `static mut` with
152// some sort of `SyncCell`, migrate all three of these to that approach
153// (https://github.com/tock/tock/issues/1545).
154static CTR: SingleThreadValue<Cell<usize>> = SingleThreadValue::new();
155
156/// This bitmask tracks which of the up to 32 existing deferred calls have been
157/// scheduled.
158///
159/// Any bit that is set in that mask indicates the deferred call with its
160/// [`DeferredCall::idx`] field set to the index of that bit has been scheduled
161/// and not yet serviced.
162static BITMASK: SingleThreadValue<Cell<u32>> = SingleThreadValue::new();
163
164/// An array that stores references to up to 32 `DeferredCall`s via the low-cost
165/// [`DynDefCallRef`].
166// This is a 256 byte array, but at least resides in `.bss`.
167static DEFCALLS: SingleThreadValue<[OptionalCell<DynDefCallRef<'static>>; 32]> =
168    SingleThreadValue::new();
169
170/// Initialize the static state used by deferred calls.
171///
172/// This ensures it can safely be used as a global variable.
173#[cfg(target_has_atomic = "ptr")]
174pub fn initialize_deferred_call_state<P: ThreadIdProvider>() {
175    let _ = CTR.bind_to_thread::<P>(Cell::new(0));
176    let _ = BITMASK.bind_to_thread::<P>(Cell::new(0));
177    let _ = DEFCALLS.bind_to_thread::<P>([const { OptionalCell::empty() }; 32]);
178}
179
180/// Initialize the static state used by deferred calls.
181///
182/// This ensures it can safely be used as a global variable.
183///
184/// # Safety
185///
186/// Callers of this function must ensure that this function is never called
187/// concurrently with calls to `initialize_deferred_call_state` or other calls
188/// to [`initialize_deferred_call_state_unsafe`].
189pub unsafe fn initialize_deferred_call_state_unsafe<P: ThreadIdProvider>() {
190    // SAFETY: See function safety description.
191    unsafe {
192        let _ = CTR.bind_to_thread_unsafe::<P>(Cell::new(0));
193        let _ = BITMASK.bind_to_thread_unsafe::<P>(Cell::new(0));
194        let _ = DEFCALLS.bind_to_thread_unsafe::<P>([const { OptionalCell::empty() }; 32]);
195    }
196}
197
198pub struct DeferredCall {
199    idx: usize,
200}
201
202impl DeferredCall {
203    /// Create a new deferred call with a unique ID.
204    pub fn new() -> Self {
205        if let Some(ctr) = CTR.get() {
206            let idx = ctr.get();
207            ctr.set(idx + 1);
208            DeferredCall { idx }
209        } else {
210            // If this panic occurs, the platform did not call
211            // `initialize_deferred_call_state()` or
212            // `initialize_deferred_call_state_unsafe()` before creating a
213            // DeferredCall.
214            //
215            // We panic here rather than return an option or result because
216            // there is no recourse for the caller. This is an unrecoverable
217            // issue in practice and a bug in the kernel. The board must call
218            // one of the initialization functions first.
219            panic!("DeferredCall state not initialized.");
220        }
221    }
222
223    // To reduce monomorphization bloat, the non-generic portion of register is
224    // moved into this function without generic parameters.
225    #[inline(never)]
226    fn register_internal_non_generic(&self, handler: DynDefCallRef<'static>) {
227        if let Some(defcalls) = DEFCALLS.get() {
228            if self.idx >= defcalls.len() {
229                // This error will be caught by the scheduler at the beginning of
230                // the kernel loop, which is much better than panicking here, before
231                // the debug writer is setup. Also allows a single panic for
232                // creating too many deferred calls instead of NUM_DCS panics (this
233                // function is monomorphized).
234                return;
235            }
236            defcalls[self.idx].set(handler);
237        }
238    }
239
240    /// This function registers the passed client with this deferred call, such
241    /// that calls to [`DeferredCall::set()`] will schedule a callback on the
242    /// [`handle_deferred_call()`](DeferredCallClient::handle_deferred_call)
243    /// method of the passed client.
244    pub fn register<DC: DeferredCallClient>(&self, client: &'static DC) {
245        let handler = DynDefCallRef::new(client);
246        self.register_internal_non_generic(handler);
247    }
248
249    /// Schedule a deferred callback on the client associated with this deferred
250    /// call.
251    pub fn set(&self) {
252        if let Some(bitmask) = BITMASK.get() {
253            bitmask.set(bitmask.get() | (1 << self.idx));
254        }
255    }
256
257    /// Check if a deferred callback has been set and not yet serviced on this
258    /// deferred call.
259    pub fn is_pending(&self) -> bool {
260        if let Some(bitmask) = BITMASK.get() {
261            bitmask.get() & (1 << self.idx) != 0
262        } else {
263            false
264        }
265    }
266
267    /// Services and clears the next pending [`DeferredCall`], returns which
268    /// index was serviced.
269    pub fn service_next_pending() -> Option<usize> {
270        let defcalls = DEFCALLS.get()?;
271        let bitmask = BITMASK.get()?;
272        let val = bitmask.get();
273        if val == 0 {
274            None
275        } else {
276            let bit = val.trailing_zeros() as usize;
277            let new_val = val & !(1 << bit);
278            bitmask.set(new_val);
279            defcalls[bit].map(|dc| {
280                dc.handle_deferred_call();
281                bit
282            })
283        }
284    }
285
286    /// Returns true if any deferred calls are waiting to be serviced, false
287    /// otherwise.
288    pub fn has_tasks() -> bool {
289        BITMASK.get().is_some_and(|b| b.get() != 0)
290    }
291
292    /// This function should be called at the beginning of the kernel loop to
293    /// verify that deferred calls have been correctly initialized. This
294    /// function verifies three things:
295    ///
296    /// 1. That `DEFCALLS` and the other [`SingleThreadValue`] types have been
297    ///    bound to a thread. This happens during
298    ///    `initialize_deferred_call_state` or
299    ///    [`initialize_deferred_call_state_unsafe`].
300    ///
301    /// 2. That <= `DEFCALLS::len` deferred calls have been created, which is
302    ///    the maximum this interface supports.
303    ///
304    /// 3. That exactly as many deferred calls were registered as were created,
305    ///    which helps to catch bugs if board maintainers forget to call
306    ///    [`register()`](DeferredCall::register) on a created [`DeferredCall`].
307    ///
308    /// None of these checks is necessary for soundness, but they are
309    /// necessary for confirming that [`DeferredCall`]s will actually be
310    /// delivered as expected. This function costs about 300 bytes, so you can
311    /// remove it if you are confident your setup will not exceed 32 deferred
312    /// calls, and that all of your components register their deferred calls.
313    // Ignore the clippy warning for using `.filter(|opt| opt.is_some())` since
314    // we don't actually have an Option (we have an OptionalCell) and
315    // IntoIterator is not implemented for OptionalCell.
316    #[allow(clippy::iter_filter_is_some)]
317    pub fn verify_setup() {
318        if let Some(defcalls) = DEFCALLS.get() {
319            if let Some(ctr) = CTR.get() {
320                let num_deferred_calls = ctr.get();
321                let num_registered_calls = defcalls.iter().filter(|opt| opt.is_some()).count();
322                if num_deferred_calls > defcalls.len() {
323                    panic!("ERROR: too many deferred calls: {}", num_deferred_calls);
324                } else if num_deferred_calls != num_registered_calls {
325                    panic!(
326                        "ERROR: {} deferred calls, {} registered. \
327A component may have forgotten to register a deferred call.",
328                        num_deferred_calls, num_registered_calls
329                    );
330                }
331            }
332        } else {
333            // The board must call initialize_deferred_call_state() or
334            // initialize_deferred_call_state_unsafe() before creating any
335            // deferred calls.
336            panic!("ERROR: deferred calls not initialized.");
337        }
338    }
339}