Skip to main content

sel4/state/
mod.rs

1//
2// Copyright 2023, Colias Group, LLC
3//
4// SPDX-License-Identifier: MIT
5//
6
7use core::cell::UnsafeCell;
8
9use crate::{InvocationContext, IpcBuffer};
10
11mod token;
12
13#[allow(unused_imports)]
14use token::{Accessor, BorrowError, BorrowMutError, SyncToken, TokenCell, UnsyncToken};
15
16// // //
17
18#[repr(transparent)]
19struct SyncUnsafeCell<T>(UnsafeCell<T>);
20
21unsafe impl<T: Sync> Sync for SyncUnsafeCell<T> {}
22
23#[repr(transparent)]
24struct TokenCellWrapper<A>(TokenCell<TokenImpl, A>);
25
26cfg_select! {
27    all(
28        any(target_thread_local, feature = "tls"),
29        not(feature = "non-thread-local-state")
30    ) => {
31        type TokenImpl = UnsyncToken;
32
33        const STATE_IS_THREAD_LOCAL: bool = true;
34
35        macro_rules! maybe_add_thread_local_attr {
36            { $item:item } => {
37                #[thread_local]
38                $item
39            }
40        }
41    }
42    not(feature = "thread-local-state") => {
43        cfg_select! {
44            feature = "single-threaded" => {
45                unsafe impl<A> Sync for TokenCellWrapper<A> {}
46
47                type TokenImpl = UnsyncToken;
48            }
49            _ => {
50                type TokenImpl = SyncToken;
51            }
52        }
53
54        const STATE_IS_THREAD_LOCAL: bool = false;
55
56        macro_rules! maybe_add_thread_local_attr {
57            { $item:item } => {
58                $item
59            }
60        }
61    }
62    _ => {
63        compile_error!(r#"invalid configuration"#);
64    }
65}
66
67macro_rules! maybe_extern {
68    { $ident:ident: $ty:ty = $init:expr; } => {
69        cfg_select! {
70            feature = "extern-state" => {
71                unsafe extern "C" {
72                    maybe_add_thread_local_attr! {
73                        static $ident: $ty;
74                    }
75                }
76            }
77            _ => {
78                maybe_add_thread_local_attr! {
79                    #[allow(non_upper_case_globals)]
80                    #[cfg_attr(feature = "exposed-state", unsafe(no_mangle))]
81                    static $ident: $ty = $init;
82                }
83            }
84        }
85    }
86}
87
88// // //
89
90maybe_extern! {
91    __sel4_ipc_buffer: SyncUnsafeCell<Option<&'static mut IpcBuffer>> =
92        SyncUnsafeCell(UnsafeCell::new(None));
93}
94
95struct IpcBufferAccessor;
96
97impl Accessor<Option<&'static mut IpcBuffer>> for IpcBufferAccessor {
98    #[allow(unused_unsafe)]
99    fn with<F, U>(&self, f: F) -> U
100    where
101        F: FnOnce(&UnsafeCell<Option<&'static mut IpcBuffer>>) -> U,
102    {
103        f(unsafe { &__sel4_ipc_buffer.0 })
104    }
105}
106
107maybe_add_thread_local_attr! {
108    static IPC_BUFFER: TokenCellWrapper<IpcBufferAccessor> = unsafe {
109        TokenCellWrapper(TokenCell::new(IpcBufferAccessor))
110    };
111}
112
113/// Provides low-level access to this thread's IPC buffer.
114///
115/// This function does not modify kernel state. It only affects this crate's thread-local state.
116///
117/// Requires the `"state"` feature to be enabled.
118pub fn try_with_ipc_buffer_slot<F, T>(f: F) -> T
119where
120    F: FnOnce(Result<&Option<&'static mut IpcBuffer>, BorrowError>) -> T,
121{
122    IPC_BUFFER.0.try_with(f)
123}
124
125/// Provides low-level mutable access to this thread's IPC buffer.
126///
127/// This function does not modify kernel state. It only affects this crate's thread-local state.
128///
129/// Requires the `"state"` feature to be enabled.
130pub fn try_with_ipc_buffer_slot_mut<F, T>(f: F) -> T
131where
132    F: FnOnce(Result<&mut Option<&'static mut IpcBuffer>, BorrowMutError>) -> T,
133{
134    IPC_BUFFER.0.try_with_mut(f)
135}
136
137/// Provides access to this thread's IPC buffer.
138///
139/// Requires the `"state"` feature to be enabled.
140pub fn with_ipc_buffer<F, T>(f: F) -> T
141where
142    F: FnOnce(&IpcBuffer) -> T,
143{
144    try_with_ipc_buffer_slot(|buf| {
145        f(buf
146            .expect("IPC buffer already mutably borrowed")
147            .as_ref()
148            .expect("IPC buffer not set"))
149    })
150}
151
152/// Provides mutable access to this thread's IPC buffer.
153///
154/// Requires the `"state"` feature to be enabled.
155pub fn with_ipc_buffer_mut<F, T>(f: F) -> T
156where
157    F: FnOnce(&mut IpcBuffer) -> T,
158{
159    try_with_ipc_buffer_slot_mut(|buf| {
160        f(buf
161            .expect("IPC buffer already borrowed")
162            .as_mut()
163            .expect("IPC buffer not set"))
164    })
165}
166
167/// Sets the IPC buffer that this crate will use for this thread.
168///
169/// This function does not modify kernel state. It only affects this crate's thread-local state.
170///
171/// Requires the `"state"` feature to be enabled.
172pub fn set_ipc_buffer(ipc_buffer: &'static mut IpcBuffer) {
173    try_with_ipc_buffer_slot_mut(|slot| {
174        *slot.unwrap() = Some(ipc_buffer);
175    })
176}
177
178/// Returns whether this crate's IPC buffer slot is thread-local.
179///
180/// Requires the `"state"` feature to be enabled.
181pub const fn ipc_buffer_is_thread_local() -> bool {
182    STATE_IS_THREAD_LOCAL
183}
184
185/// The strategy for discovering the current thread's IPC buffer which uses thread-local state.
186///
187/// This thread-local state can be modified using [`with_ipc_buffer`] and [`set_ipc_buffer`].
188///
189/// Requires the `"state"` feature to be enabled.
190#[derive(Debug, Copy, Clone, Default, PartialEq, Eq, Hash)]
191pub struct ImplicitInvocationContext;
192
193impl ImplicitInvocationContext {
194    pub const fn new() -> Self {
195        Self
196    }
197}
198
199impl InvocationContext for ImplicitInvocationContext {
200    fn with_context<T>(&mut self, f: impl FnOnce(&mut IpcBuffer) -> T) -> T {
201        with_ipc_buffer_mut(f)
202    }
203}