1#![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 #[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 fn early_init(self) {}
106
107 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 #[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#[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 stack: unsafe { &mut BOOTSTRAP_STACK },
255 },
256 idle_thread: $crate::ThreadStorage {
257 thread: $crate::Thread::new("idle", Priority::IDLE_PRIORITY, $crate::Stack::new()),
258 stack: unsafe { &mut IDLE_STACK},
261 },
262 }
263 };
264
265 $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 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#[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 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 scheduler::bootstrap_scheduler(kernel, preempt_guard, bootstrap_thread);
338
339 }
341
342fn 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 pw_assert::assert!(K::InterruptController::interrupts_enabled());
370 loop {
371 kernel.idle();
372 }
373}
374
375pub 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 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 #[doc(hidden)] #[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 let value = $value;
428
429 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}