Skip to main content Skip to main content
Pigweed's logo Pigweed
code_xml
  1. Home
  2. Reference
  3. Rust
  4. pw_kernel
  5. src
  6. kernel/lib.rs

kernel/
lib.rs

1// Copyright 2025 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14#![no_std]
15
16use pw_atomic::{AtomicBool, AtomicUsize};
17use pw_log::info;
18pub use pw_time_core::{Duration, Instant};
19
20pub mod interrupt_controller;
21#[cfg(feature = "user_space")]
22pub mod object;
23#[cfg(not(feature = "std_panic_handler"))]
24mod panic;
25pub mod scheduler;
26pub mod sync;
27#[cfg(feature = "user_space")]
28pub mod syscall;
29pub use target::shutdown;
30mod target;
31pub mod trace;
32
33use interrupt_controller::InterruptController;
34use kernel_config::{KernelConfig, KernelConfigInterface};
35#[cfg(feature = "user_space")]
36pub use object::NullObjectTable;
37use scheduler::{PreemptDisableGuard, SchedulerState, ThreadLocalState, TimerQueue};
38pub use scheduler::{Priority, sleep_until, start_thread, yield_timeslice};
39#[doc(hidden)]
40pub use scheduler::{Process, Stack, StackStorage, StackStorageExt, Thread, ThreadState};
41use sync::spinlock::{BareSpinLock, SpinLock, SpinLockGuard};
42#[cfg(feature = "user_space")]
43pub use syscall::SyscallArgs;
44
45pub trait Arch: 'static + Copy + scheduler::ThreadArg {
46    type ThreadState: ThreadState;
47    type BareSpinLock: BareSpinLock;
48    type Clock: pw_time_core::Clock;
49    type AtomicBool: AtomicBool;
50    type AtomicUsize: AtomicUsize;
51    #[cfg(feature = "user_space")]
52    type SyscallArgs<'a>: SyscallArgs<'a>;
53    type InterruptController: InterruptController;
54
55    /// Switches to a new thread.
56    ///
57    /// - `sched_state`: A guard for the global `SchedulerState`
58    ///   - This may be dropped and re-acquired across this function; the
59    ///     returned guard is either still held or newly re-acquired
60    /// - `old_thread_state`: The thread we're moving away from
61    /// - `new_thread_state`: The thread we're moving to; must match
62    ///   `current_thread` and the container for this `ThreadState`
63    ///
64    /// Returns:
65    /// - `sched_state`: A guard for the global `SchedulerState`
66    /// - `switched`: `true` if a context switch happened, `false` otherwise.
67    ///
68    /// If `switched` is `false`, the implementation guarantees that forward
69    /// progress will be made. For example, a context switch may be deferred
70    /// to an interrupt handler (like PendSV) which is pending. The caller
71    /// does not need to retry or take further action to ensure the switch
72    /// occurs.
73    #[allow(clippy::missing_safety_doc)]
74    unsafe fn context_switch(
75        self,
76        sched_state: SpinLockGuard<'_, Self, SchedulerState<Self>>,
77        old_thread_state: *mut Self::ThreadState,
78        new_thread_state: *mut Self::ThreadState,
79    ) -> (SpinLockGuard<'_, Self, SchedulerState<Self>>, bool)
80    where
81        Self: Kernel;
82
83    fn thread_local_state(self) -> &'static ThreadLocalState<Self>;
84
85    fn now(self) -> Instant<Self::Clock>;
86
87    fn get_interrupt_controller(self) -> &'static SpinLock<Self, Self::InterruptController>
88    where
89        Self: Kernel,
90    {
91        &self.get_state().arch_state.interrupt_controller
92    }
93
94    #[allow(dead_code)]
95    fn idle(self) {}
96
97    /// Early architecture initialization, called before the scheduler is bootstrapped.
98    ///
99    /// This is invoked during kernel startup before any threads exist and before
100    /// the scheduler is operational. Architecture code **must not** call
101    /// `scheduler::tick()` or any other scheduler functions during this phase.
102    ///
103    /// Use this for hardware initialization that must happen before the scheduler
104    /// starts, such as setting up the interrupt controller or memory protection.
105    fn early_init(self) {}
106
107    /// Architecture initialization, called after the scheduler is bootstrapped.
108    ///
109    /// This is invoked after the scheduler is fully operational and threads can
110    /// be scheduled. It is safe to call `scheduler::tick()` once `init()` is invoked.
111    ///
112    /// Use this for initialization that depends on the scheduler being ready,
113    /// such as starting timer interrupts that will drive `scheduler::tick()`.
114    ///
115    /// # Contract
116    ///
117    /// - `early_init()` is always called before `init()`
118    /// - `scheduler::tick()` **must not** be called by architecture code before
119    ///   `init()` is invoked
120    /// - Once `init()` is invoked, timer interrupts may safely call `scheduler::tick()`.
121    ///   This includes interrupts that fire before `init()` returns. At this point,
122    ///   only the bootstrap thread exists in the system and any context switch
123    ///   requests will early exit, making this safe.
124    fn init(self) {}
125
126    fn panic() -> ! {
127        #[allow(clippy::empty_loop)]
128        loop {}
129    }
130}
131
132pub struct ArchState<K: Kernel> {
133    interrupt_controller: SpinLock<K, K::InterruptController>,
134}
135
136impl<K: Kernel> ArchState<K> {
137    #[must_use]
138    pub const fn new(interrupt_controller: K::InterruptController) -> Self {
139        Self {
140            interrupt_controller: SpinLock::new(interrupt_controller),
141        }
142    }
143}
144
145pub trait Kernel: Arch + Sync {
146    fn get_state(self) -> &'static KernelState<Self>;
147
148    fn get_scheduler(self) -> &'static SpinLock<Self, SchedulerState<Self>> {
149        &self.get_state().scheduler
150    }
151
152    fn get_timer_queue(self) -> &'static SpinLock<Self, TimerQueue<Self>> {
153        &self.get_state().timer_queue
154    }
155}
156
157pub struct KernelState<K: Kernel> {
158    arch_state: ArchState<K>,
159    scheduler: SpinLock<K, SchedulerState<K>>,
160    timer_queue: SpinLock<K, TimerQueue<K>>,
161
162    // TODO: https://pwbug.dev/479857256 - Add configurable trace buffer size.
163    #[cfg(feature = "tracing")]
164    pub trace_buffer: pw_kernel_tracing::Buffer<K::AtomicUsize, 2048>,
165}
166
167impl<K: Kernel> KernelState<K> {
168    #[must_use]
169    pub const fn new(arch_state: ArchState<K>) -> Self {
170        Self {
171            arch_state,
172            scheduler: SpinLock::new(SchedulerState::new()),
173            timer_queue: SpinLock::new(TimerQueue::new()),
174            #[cfg(feature = "tracing")]
175            trace_buffer: pw_kernel_tracing::Buffer::new(),
176        }
177    }
178}
179
180#[cfg(not(feature = "tracing"))]
181#[macro_export]
182macro_rules! annotate_kernel_trace_buffer {
183    ($trace_buffer:expr) => {{}};
184}
185
186#[cfg(feature = "tracing")]
187#[macro_export]
188macro_rules! annotate_kernel_trace_buffer {
189    ($trace_buffer:expr) => {{
190        #[repr(C, packed(1))]
191        struct TraceBufferAnnotation {
192            name: &'static str,
193            addr: *const (),
194            size: usize,
195        }
196        unsafe impl Sync for TraceBufferAnnotation {};
197
198        #[unsafe(link_section = ".pw_kernel.annotations.trace_buffer")]
199        #[used]
200        static _TRACE_BUFFER_ANNOTATION: TraceBufferAnnotation = TraceBufferAnnotation {
201            name: "kernel",
202            addr: unsafe { $trace_buffer.buffer() },
203            size: $trace_buffer.buffer_len(),
204        };
205    }};
206}
207
208#[macro_export]
209macro_rules! annotate_kernel_state {
210    ($state:expr) => {{ $crate::annotate_kernel_trace_buffer!($state.trace_buffer) }};
211}
212
213/// Initializes an [`InitKernelState`] in static storage.
214///
215/// # Examples
216///
217/// Here's an example of using `static_init_state!` on Cortex-M:
218///
219/// ```
220/// struct Arch;
221///
222/// #[cortex_m_rt::entry]
223/// fn main() -> ! {
224///     Target::console_init();
225///
226///     kernel::static_init_state!(static mut INIT_STATE: InitKernelState<Arch>);
227///
228///     // SAFETY: `main` is only executed once, so we never generate more than one
229///     // `&mut` reference to `INIT_STATE`.
230///     kernel::Kernel::main(Arch, unsafe { &mut INIT_STATE });
231/// }
232/// ```
233#[macro_export]
234macro_rules! static_init_state {
235    ($vis:vis static mut $name:ident: InitKernelState<$kernel:ty>) => {
236        $vis static mut $name: $crate::InitKernelState<$kernel> = {
237            use $crate::__private::kernel_config;
238            use kernel_config::KernelConfigInterface as _;
239            use kernel::StackStorageExt as _;
240            use $crate::Priority;
241
242            type Stack = $crate::StackStorage<{ kernel_config::KernelConfig::KERNEL_STACK_SIZE_BYTES }>;
243            static mut BOOTSTRAP_STACK: Stack = Stack::ZEROED;
244            static mut IDLE_STACK: Stack = Stack::ZEROED;
245
246            $crate::annotate_stack!("bootstrap", &raw const BOOTSTRAP_STACK, kernel_config::KernelConfig::KERNEL_STACK_SIZE_BYTES);
247            $crate::annotate_stack!("idle", &raw const IDLE_STACK, kernel_config::KernelConfig::KERNEL_STACK_SIZE_BYTES);
248
249            $crate::InitKernelState {
250                bootstrap_thread: $crate::ThreadStorage {
251                    thread: $crate::Thread::new("bootstrap", Priority::DEFAULT_PRIORITY, $crate::Stack::new()),
252                    // SAFETY: We're in a block used to initialize a `static`,
253                    // which is only executed once.
254                    stack: unsafe { &mut BOOTSTRAP_STACK },
255                },
256                idle_thread: $crate::ThreadStorage {
257                    thread: $crate::Thread::new("idle", Priority::IDLE_PRIORITY, $crate::Stack::new()),
258                    // SAFETY: We're in a block used to initialize a `static`,
259                    // which is only executed once.
260                    stack: unsafe { &mut IDLE_STACK},
261                },
262            }
263        };
264
265        // A null address is used as the ID of the kernel process for annotations
266        // due to not being able to access the address of the kernel process
267        // from here.
268        $crate::annotate_thread_from_address!(
269            "bootstrap",
270            $kernel,
271            &raw const $name.bootstrap_thread.thread,
272            core::ptr::null());
273        $crate::annotate_thread_from_address!(
274            "idle",
275            $kernel,
276            &raw const $name.idle_thread.thread,
277            core::ptr::null());
278    };
279}
280
281#[doc(hidden)]
282pub struct ThreadStorage<K: Kernel> {
283    pub thread: Thread<K>,
284    // We store the stack out of line so that it is treated as a separate
285    // allocation from the containing `ThreadStorage`. The stack itself is
286    // zero-initialized, while the `Thread` is not. If we include the stack in
287    // the same allocation, then the entire allocation must be placed in the
288    // binary itself (in `.data`). By contrast, if it is out of line, then the
289    // fact that the whole stack is zero-initialized means that the linker can
290    // put it in `.bss` and omit its contents from the binary entirely.
291    //
292    // See https://pwrev.dev/303372 (Ie93cfc52215753e1b4482d5fe3058dc53fcfa86a)
293    // for more information.
294    pub stack: &'static mut StackStorage<{ KernelConfig::KERNEL_STACK_SIZE_BYTES }>,
295}
296
297pub struct InitKernelState<K: Kernel> {
298    #[doc(hidden)]
299    pub bootstrap_thread: ThreadStorage<K>,
300    #[doc(hidden)]
301    pub idle_thread: ThreadStorage<K>,
302}
303
304// Module re-exporting modules into a scope that can be referenced by macros
305// in this crate.
306#[doc(hidden)]
307pub mod macro_exports {
308    pub use foreign_box;
309    pub use pw_assert;
310}
311
312pub fn main<K: Kernel>(kernel: K, init_state: &'static mut InitKernelState<K>) -> ! {
313    let preempt_guard = PreemptDisableGuard::new(kernel);
314
315    kernel.get_interrupt_controller().lock(kernel).early_init();
316
317    target::console_init();
318    info!("Welcome to Maize on {}!", target::name() as &str);
319
320    kernel.early_init();
321
322    // Prepare the scheduler for thread initialization.
323    scheduler::initialize(kernel);
324
325    let bootstrap_thread = scheduler::init_thread_in(
326        kernel,
327        &mut init_state.bootstrap_thread.thread,
328        init_state.bootstrap_thread.stack,
329        "bootstrap",
330        Priority::DEFAULT_PRIORITY,
331        bootstrap_thread_entry,
332        &mut init_state.idle_thread,
333    );
334    info!("Created initial thread; bootstrapping");
335
336    // special case where we bootstrap the system by half context switching to this thread
337    scheduler::bootstrap_scheduler(kernel, preempt_guard, bootstrap_thread);
338
339    // never get to here
340}
341
342// completion of main in thread context
343fn bootstrap_thread_entry<K: Kernel>(
344    kernel: K,
345    idle_thread_storage: &'static mut ThreadStorage<K>,
346) {
347    info!("Welcome to the first thread, continuing bootstrap");
348    pw_assert::assert!(K::InterruptController::interrupts_enabled());
349
350    kernel.init();
351
352    let idle_thread = scheduler::init_thread_in(
353        kernel,
354        &mut idle_thread_storage.thread,
355        idle_thread_storage.stack,
356        "idle",
357        Priority::IDLE_PRIORITY,
358        idle_thread_entry,
359        0,
360    );
361
362    scheduler::start_thread(kernel, idle_thread);
363
364    target::main()
365}
366
367fn idle_thread_entry<K: Kernel>(kernel: K, _arg: usize) {
368    // Fake idle thread to keep the runqueue from being empty if all threads are blocked.
369    pw_assert::assert!(K::InterruptController::interrupts_enabled());
370    loop {
371        kernel.idle();
372    }
373}
374
375/// Stores `t` in stack memory and provides a `&'static mut T` to a function
376/// which will never return.
377///
378/// Since `F: FnOnce(...) -> !`, the stack memory holding `t` will never be
379/// reclaimed, and so it can live forever (ie, be referenced using `&'static mut
380/// T`).
381///
382/// If `f` unwinds, `with_static` will `loop {}` forever to prevent `t` from
383/// being reclaimed.
384pub fn with_static<T: 'static, F: FnOnce(&'static mut T)>(t: T, f: F) -> ! {
385    struct LoopOnDrop<T>(T);
386    impl<T> Drop for LoopOnDrop<T> {
387        fn drop(&mut self) {
388            #[allow(clippy::empty_loop)]
389            loop {}
390        }
391    }
392
393    let mut t = LoopOnDrop(t);
394    let tp: *mut T = &mut t.0;
395
396    // SAFETY: Since we `drop(t)` after the `loop {}`, `t` will only go out of
397    // scope if `f` unwinds. If this happens, `LoopOnDrop::drop` will `loop {}`
398    // forever before its inner `T` is destructed. Thus, `t.0` will never be
399    // destructed, and so it is sound to synthesize a `'static` reference to
400    // `t`.
401    //
402    // See for more analysis: https://github.com/rust-lang/unsafe-code-guidelines/issues/565
403    f(unsafe { &mut *tp });
404
405    #[allow(clippy::empty_loop)]
406    loop {}
407    #[allow(unreachable_code)]
408    drop(t);
409}
410
411#[doc(hidden)]
412pub mod __private {
413    /// Takes a mutable reference to a global static.
414    ///
415    /// # Safety
416    ///
417    /// Each invocation of `static_mut_ref!` must be executed at most once at
418    /// run time.
419    #[doc(hidden)] // `#[macro_export]` bypasses this module's `#[doc(hidden)]`
420    #[macro_export]
421    macro_rules! static_mut_ref {
422        ($ty:ty = $value:expr) => {{
423            use $crate::__private::foreign_box::StaticStorage;
424            static mut __STATIC: StaticStorage<$ty> = StaticStorage::new();
425
426            // Alias value to allow nested `unsafe` statements without warning.
427            let value = $value;
428
429            // SAFETY: The caller promises that this macro will be executed at
430            // most once fulfilling `StaticStorage`'s precondition.
431            unsafe { __STATIC.init(value) }
432        }};
433    }
434
435    pub use foreign_box;
436    pub use kernel_config;
437    #[cfg(feature = "tracing")]
438    pub use pw_tokenizer;
439}