Skip to main content

rrkernel/
thread.rs

1//! `thread::spawn` — the entire task-creation surface.
2//!
3//! There is deliberately no `JoinHandle`, no `Result` from the spec'd entry
4//! point, and no way to wait on a task: joining would need a blocking
5//! primitive, and this kernel has none. A task runs until its closure returns,
6//! then the trampoline unlinks it. (`try_spawn` exists for callers who want
7//! allocation failure as a value instead of a panic.)
8
9use crate::config::ConfigError;
10use core::fmt;
11
12/// Default per-task stack size when the caller does not specify one.
13///
14/// 4 KiB is a sane floor for a Cortex-M task and plenty for a host fiber.
15/// Override globally with [`crate::SchedulerConfig::stack_size`] or per task
16/// with [`spawn_with_stack`].
17pub const DEFAULT_STACK_SIZE: usize = 4096;
18
19/// Why a spawn failed.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum SpawnError {
22    /// `scheduler::init*` has not run yet, or the arena is not set up.
23    NotInitialized,
24    /// Not enough space left in the kernel arena for the TCB / closure /
25    /// stack. Increase the arena (bare metal: `SchedulerConfig::arena`).
26    ArenaExhausted,
27    /// The OS refused to create the execution context (Win32 thread / POSIX
28    /// fiber).
29    Backend(ConfigError),
30}
31
32impl fmt::Display for SpawnError {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match *self {
35            SpawnError::NotInitialized => {
36                write!(f, "scheduler not initialized (call scheduler::init first)")
37            }
38            SpawnError::ArenaExhausted => write!(
39                f,
40                "kernel arena exhausted: increase the arena or reduce per-task stacks"
41            ),
42            SpawnError::Backend(e) => write!(f, "backend could not create the task: {e}"),
43        }
44    }
45}
46
47/// Spawn a new task into the live scheduler ring.
48///
49/// Callable from `main()` (before it returns) or from inside any running task,
50/// including recursively from a task that was itself spawned by a task.
51///
52/// * The new task is linked into the ring immediately, right after the
53///   *current* task, so it runs on the very next switch rather than after a
54///   full lap.
55/// * `KERNEL.total_threads` and `KERNEL.active_threads` are both incremented.
56/// * An immediate context switch is requested and the slice counter is
57///   restarted, so the newcomer registers instantly with a full slice.
58///
59/// The closure must be `'static`: a task may outlive the frame that spawned
60/// it, so nothing borrowed from the parent's stack is sound here.
61///
62/// # Panics
63/// Panics if the arena is exhausted or the scheduler is not initialised —
64/// matching `std::thread::spawn`. Use [`try_spawn`] to handle those as values.
65pub fn spawn<F>(f: F)
66where
67    F: FnOnce() + Send + 'static,
68{
69    spawn_with_stack(f, crate::scheduler::config().stack_size)
70}
71
72/// Like [`spawn`], with an explicit stack size in bytes.
73///
74/// Bare metal: exactly the reserved PSP stack. POSIX fibers: the fiber stack.
75/// Win32: the OS thread's stack reservation.
76///
77/// # Panics
78/// See [`spawn`].
79pub fn spawn_with_stack<F>(f: F, stack_size: usize)
80where
81    F: FnOnce() + Send + 'static,
82{
83    if let Err(e) = try_spawn_with_stack(f, stack_size) {
84        panic!("rrkernel: thread::spawn failed: {}", e);
85    }
86}
87
88/// [`spawn`] with the failure as a value.
89pub fn try_spawn<F>(f: F) -> Result<(), SpawnError>
90where
91    F: FnOnce() + Send + 'static,
92{
93    try_spawn_with_stack(f, crate::scheduler::config().stack_size)
94}
95
96/// [`spawn_with_stack`] with the failure as a value.
97pub fn try_spawn_with_stack<F>(f: F, stack_size: usize) -> Result<(), SpawnError>
98where
99    F: FnOnce() + Send + 'static,
100{
101    let stack_size = if stack_size == 0 {
102        DEFAULT_STACK_SIZE
103    } else {
104        stack_size
105    };
106    // SAFETY: `spawn_internal` takes the kernel critical section itself, so it
107    // is safe to call from any task or from `main`.
108    unsafe { crate::scheduler::spawn_internal(f, stack_size) }
109}