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`). Using a trait object will include a 20 byte
107/// vtable per instance, but this alternative stores only the data and function
108/// pointers, 8 bytes per instance.
109#[derive(Copy, Clone)]
110struct DynDefCallRef<'a> {
111    data: *const (),
112    callback: fn(*const ()),
113    _lifetime: PhantomData<&'a ()>,
114}
115
116impl<'a> DynDefCallRef<'a> {
117    // SAFETY: We define the callback function as being a closure which casts
118    // the passed pointer to be the appropriate type (a pointer to `T`) and then
119    // calls `T::handle_deferred_call()`. In practice, the closure is optimized
120    // away by LLVM when the ABI of the closure and the underlying function are
121    // identical, making this zero-cost, but saving us from having to trust that
122    // `fn(*const ())` and `fn handle_deferred_call(&self)` will always have the
123    // same calling convention for any type.
124    fn new<T: DeferredCallClient>(x: &'a T) -> Self {
125        let data: *const () = core::ptr::from_ref(x).cast();
126        Self {
127            data,
128            callback: |p| unsafe { T::handle_deferred_call(&*p.cast()) },
129            _lifetime: PhantomData,
130        }
131    }
132}
133
134impl DynDefCallRef<'_> {
135    // More efficient to pass by `self` if we don't have to implement
136    // `DeferredCallClient` directly.
137    fn handle_deferred_call(self) {
138        (self.callback)(self.data)
139    }
140}
141
142/// Counter for the number of deferred calls that have been created, this is
143/// used to track that no more than 32 deferred calls have been created.
144// All 3 of the below global statics are accessed only in this file, and all
145// accesses are via immutable references. Tock is single threaded, so each will
146// only ever be accessed via an immutable reference from the single kernel
147// thread. TODO: Once Tock decides on an approach to replace `static mut` with
148// some sort of `SyncCell`, migrate all three of these to that approach
149// (https://github.com/tock/tock/issues/1545).
150static CTR: SingleThreadValue<Cell<usize>> = SingleThreadValue::new();
151
152/// This bitmask tracks which of the up to 32 existing deferred calls have been
153/// scheduled. Any bit that is set in that mask indicates the deferred call with
154/// its [`DeferredCall::idx`] field set to the index of that bit has been
155/// scheduled and not yet serviced.
156static BITMASK: SingleThreadValue<Cell<u32>> = SingleThreadValue::new();
157
158/// An array that stores references to up to 32 `DeferredCall`s via the low-cost
159/// [`DynDefCallRef`].
160// This is a 256 byte array, but at least resides in `.bss`.
161static DEFCALLS: SingleThreadValue<[OptionalCell<DynDefCallRef<'static>>; 32]> =
162    SingleThreadValue::new();
163
164/// Initialize the static state used by deferred calls.
165///
166/// This ensures it can safely be used as a global variable.
167#[cfg(target_has_atomic = "ptr")]
168pub fn initialize_deferred_call_state<P: ThreadIdProvider>() {
169    let _ = CTR.bind_to_thread::<P>(Cell::new(0));
170    let _ = BITMASK.bind_to_thread::<P>(Cell::new(0));
171    let _ = DEFCALLS.bind_to_thread::<P>([const { OptionalCell::empty() }; 32]);
172}
173
174/// Initialize the static state used by deferred calls.
175///
176/// This ensures it can safely be used as a global variable.
177///
178/// # Safety
179///
180/// Callers of this function must ensure that this function is never called
181/// concurrently with calls to `initialize_deferred_call_state` or other calls
182/// to [`initialize_deferred_call_state_unsafe`].
183pub unsafe fn initialize_deferred_call_state_unsafe<P: ThreadIdProvider>() {
184    // # Safety
185    //
186    // See function safety description.
187    unsafe {
188        let _ = CTR.bind_to_thread_unsafe::<P>(Cell::new(0));
189        let _ = BITMASK.bind_to_thread_unsafe::<P>(Cell::new(0));
190        let _ = DEFCALLS.bind_to_thread_unsafe::<P>([const { OptionalCell::empty() }; 32]);
191    }
192}
193
194pub struct DeferredCall {
195    idx: usize,
196}
197
198impl DeferredCall {
199    /// Create a new deferred call with a unique ID.
200    pub fn new() -> Self {
201        if let Some(ctr) = CTR.get() {
202            let idx = ctr.get();
203            ctr.set(idx + 1);
204            DeferredCall { idx }
205        } else {
206            // If this panic occurs, the platform did not call
207            // `initialize_deferred_call_state()` or
208            // `initialize_deferred_call_state_unsafe()` before creating a
209            // DeferredCall.
210            //
211            // We panic here rather than return an option or result because
212            // there is no recourse for the caller. This is an unrecoverable
213            // issue in practice and a bug in the kernel. The board must call
214            // one of the initialization functions first.
215            panic!("DeferredCall state not initialized.");
216        }
217    }
218
219    // To reduce monomorphization bloat, the non-generic portion of register is
220    // moved into this function without generic parameters.
221    #[inline(never)]
222    fn register_internal_non_generic(&self, handler: DynDefCallRef<'static>) {
223        if let Some(defcalls) = DEFCALLS.get() {
224            if self.idx >= defcalls.len() {
225                // This error will be caught by the scheduler at the beginning of
226                // the kernel loop, which is much better than panicking here, before
227                // the debug writer is setup. Also allows a single panic for
228                // creating too many deferred calls instead of NUM_DCS panics (this
229                // function is monomorphized).
230                return;
231            }
232            defcalls[self.idx].set(handler);
233        }
234    }
235
236    /// This function registers the passed client with this deferred call, such
237    /// that calls to [`DeferredCall::set()`] will schedule a callback on the
238    /// [`handle_deferred_call()`](DeferredCallClient::handle_deferred_call)
239    /// method of the passed client.
240    pub fn register<DC: DeferredCallClient>(&self, client: &'static DC) {
241        let handler = DynDefCallRef::new(client);
242        self.register_internal_non_generic(handler);
243    }
244
245    /// Schedule a deferred callback on the client associated with this deferred
246    /// call.
247    pub fn set(&self) {
248        if let Some(bitmask) = BITMASK.get() {
249            bitmask.set(bitmask.get() | (1 << self.idx));
250        }
251    }
252
253    /// Check if a deferred callback has been set and not yet serviced on this
254    /// deferred call.
255    pub fn is_pending(&self) -> bool {
256        if let Some(bitmask) = BITMASK.get() {
257            bitmask.get() & (1 << self.idx) != 0
258        } else {
259            false
260        }
261    }
262
263    /// Services and clears the next pending [`DeferredCall`], returns which
264    /// index was serviced.
265    pub fn service_next_pending() -> Option<usize> {
266        let defcalls = DEFCALLS.get()?;
267        let bitmask = BITMASK.get()?;
268        let val = bitmask.get();
269        if val == 0 {
270            None
271        } else {
272            let bit = val.trailing_zeros() as usize;
273            let new_val = val & !(1 << bit);
274            bitmask.set(new_val);
275            defcalls[bit].map(|dc| {
276                dc.handle_deferred_call();
277                bit
278            })
279        }
280    }
281
282    /// Returns true if any deferred calls are waiting to be serviced, false
283    /// otherwise.
284    pub fn has_tasks() -> bool {
285        BITMASK.get().is_some_and(|b| b.get() != 0)
286    }
287
288    /// This function should be called at the beginning of the kernel loop to
289    /// verify that deferred calls have been correctly initialized. This
290    /// function verifies three things:
291    ///
292    /// 1. That `DEFCALLS` and the other [`SingleThreadValue`] types have been
293    ///    bound to a thread. This happens during
294    ///    `initialize_deferred_call_state` or
295    ///    [`initialize_deferred_call_state_unsafe`].
296    ///
297    /// 2. That <= `DEFCALLS::len` deferred calls have been created, which is
298    ///    the maximum this interface supports.
299    ///
300    /// 3. That exactly as many deferred calls were registered as were created,
301    ///    which helps to catch bugs if board maintainers forget to call
302    ///    [`register()`](DeferredCall::register) on a created [`DeferredCall`].
303    ///
304    /// None of these checks is necessary for soundness, but they are
305    /// necessary for confirming that [`DeferredCall`]s will actually be
306    /// delivered as expected. This function costs about 300 bytes, so you can
307    /// remove it if you are confident your setup will not exceed 32 deferred
308    /// calls, and that all of your components register their deferred calls.
309    // Ignore the clippy warning for using `.filter(|opt| opt.is_some())` since
310    // we don't actually have an Option (we have an OptionalCell) and
311    // IntoIterator is not implemented for OptionalCell.
312    #[allow(clippy::iter_filter_is_some)]
313    pub fn verify_setup() {
314        if let Some(defcalls) = DEFCALLS.get() {
315            if let Some(ctr) = CTR.get() {
316                let num_deferred_calls = ctr.get();
317                let num_registered_calls = defcalls.iter().filter(|opt| opt.is_some()).count();
318                if num_deferred_calls > defcalls.len() {
319                    panic!("ERROR: too many deferred calls: {}", num_deferred_calls);
320                } else if num_deferred_calls != num_registered_calls {
321                    panic!(
322                        "ERROR: {} deferred calls, {} registered. \
323A component may have forgotten to register a deferred call.",
324                        num_deferred_calls, num_registered_calls
325                    );
326                }
327            }
328        } else {
329            // The board must call initialize_deferred_call_state() or
330            // initialize_deferred_call_state_unsafe() before creating any
331            // deferred calls.
332            panic!("ERROR: deferred calls not initialized.");
333        }
334    }
335}