Skip to main content

ostd/
lib.rs

1// SPDX-License-Identifier: MPL-2.0
2
3#![doc = include_str!("../README.md")]
4#![feature(alloc_error_handler)]
5#![feature(allocator_api)]
6#![feature(btree_cursors)]
7#![feature(core_intrinsics)]
8#![feature(linkage)]
9#![feature(min_specialization)]
10#![feature(negative_impls)]
11#![feature(ptr_metadata)]
12#![feature(sync_unsafe_cell)]
13#![cfg_attr(target_arch = "riscv64", feature(riscv_ext_intrinsics))]
14#![cfg_attr(target_arch = "x86_64", feature(iter_advance_by, macro_metavar_expr))]
15#![expect(internal_features)]
16#![no_std]
17#![warn(missing_docs)]
18
19extern crate alloc;
20#[macro_use]
21extern crate ostd_pod;
22
23// Set this crate's log prefix for `ostd::log`.
24macro_rules! __log_prefix {
25    () => {
26        ""
27    };
28}
29
30#[cfg_attr(target_arch = "x86_64", path = "arch/x86/mod.rs")]
31#[cfg_attr(target_arch = "riscv64", path = "arch/riscv/mod.rs")]
32#[cfg_attr(target_arch = "loongarch64", path = "arch/loongarch/mod.rs")]
33#[cfg_attr(target_arch = "aarch64", path = "arch/arm/mod.rs")]
34pub mod arch;
35
36pub mod boot;
37pub mod bus;
38pub mod console;
39pub mod cpu;
40mod error;
41pub mod io;
42pub mod irq;
43pub mod log;
44pub mod mm;
45pub mod panic;
46pub mod power;
47pub mod prelude;
48pub mod smp;
49pub mod sync;
50pub mod task;
51pub mod timer;
52pub mod user;
53pub mod util;
54
55#[cfg(feature = "coverage")]
56mod coverage;
57
58use core::sync::atomic::{AtomicBool, Ordering};
59
60pub use ostd_macros::{
61    early_cmdline_parser, global_frame_allocator, global_heap_allocator,
62    global_heap_allocator_slot_map, main, panic_handler,
63};
64
65pub use self::{error::Error, prelude::Result};
66
67/// Initializes OSTD.
68///
69/// This function represents the first phase booting up the system. It makes
70/// all functionalities of OSTD available after the call.
71///
72/// # Safety
73///
74/// This function should be called only once and only on the BSP.
75//
76// TODO: We need to refactor this function to make it more modular and
77// make inter-initialization-dependencies more clear and reduce usages of
78// boot stage only global variables.
79unsafe fn init() {
80    arch::enable_cpu_features();
81
82    // SAFETY: This function is called only once, before `allocator::init`
83    // and after memory regions are initialized.
84    unsafe { mm::frame::allocator::init_early_allocator() };
85
86    let early_cmdline = boot::parse_early_cmdline();
87
88    #[cfg(target_arch = "x86_64")]
89    arch::if_tdx_enabled!({
90    } else {
91        // SAFETY: This function is called only once on the BSP.
92        unsafe { arch::serial::init(&early_cmdline) };
93    });
94    #[cfg(not(target_arch = "x86_64"))]
95    arch::serial::init(&early_cmdline);
96
97    log::init(&early_cmdline);
98
99    // SAFETY:
100    //  1. They are only called once in the boot context of the BSP.
101    //  2. The number of CPUs are available because ACPI has been initialized.
102    //  3. CPU-local storage has NOT been used.
103    unsafe { cpu::init_on_bsp() };
104
105    // SAFETY: We are on the BSP and APs are not yet started.
106    let meta_pages = unsafe { mm::frame::meta::init() };
107    // The frame allocator should be initialized immediately after the metadata
108    // is initialized. Otherwise the boot page table can't allocate frames.
109    // SAFETY: This function is called only once.
110    unsafe { mm::frame::allocator::init() };
111
112    mm::kspace::init_kernel_page_table(meta_pages);
113
114    // SAFETY: This function is called only once on the BSP.
115    unsafe { mm::kspace::activate_kernel_page_table() };
116
117    sync::init();
118
119    boot::init_after_heap();
120
121    // SAFETY: This function is called only once on the BSP.
122    unsafe { arch::late_init_on_bsp() };
123
124    #[cfg(target_arch = "x86_64")]
125    arch::if_tdx_enabled!({
126        // SAFETY: This function is called only once on the BSP.
127        unsafe { arch::serial::init(&early_cmdline) };
128    });
129
130    smp::init();
131
132    // SAFETY:
133    // 1. The kernel page table is activated on the BSP.
134    // 2. The function is called only once on the BSP.
135    // 3. No remaining `with_borrow` invocations from now.
136    unsafe { mm::page_table::boot_pt::dismiss() };
137
138    arch::irq::enable_local();
139
140    invoke_ffi_init_funcs();
141
142    IN_BOOTSTRAP_CONTEXT.store(false, Ordering::Relaxed);
143}
144
145/// Indicates whether the kernel is in bootstrap context.
146pub(crate) static IN_BOOTSTRAP_CONTEXT: AtomicBool = AtomicBool::new(true);
147
148/// Invoke the initialization functions defined in the FFI.
149/// The component system uses this function to call the initialization functions of
150/// the components.
151fn invoke_ffi_init_funcs() {
152    unsafe extern "C" {
153        fn __sinit_array();
154        fn __einit_array();
155    }
156    let call_len = (__einit_array as *const () as usize - __sinit_array as *const () as usize) / 8;
157    for i in 0..call_len {
158        unsafe {
159            let function = (__sinit_array as *const () as usize + 8 * i) as *const fn();
160            (*function)();
161        }
162    }
163}
164
165mod feature_validation {
166    #[cfg(all(not(target_arch = "riscv64"), feature = "riscv_sv39_mode"))]
167    compile_error!(
168        "feature \"riscv_sv39_mode\" cannot be specified for architectures other than RISC-V"
169    );
170}
171
172/// Simple unit tests for the ktest framework.
173#[cfg(ktest)]
174mod test {
175    use crate::prelude::*;
176
177    #[expect(clippy::eq_op)]
178    #[ktest]
179    fn trivial_assertion() {
180        assert_eq!(0, 0);
181    }
182
183    #[ktest]
184    #[should_panic]
185    fn failing_assertion() {
186        assert_eq!(0, 1);
187    }
188
189    #[ktest]
190    #[should_panic(expected = "expected panic message")]
191    fn expect_panic() {
192        panic!("expected panic message");
193    }
194}
195
196#[doc(hidden)]
197pub mod ktest {
198    //! The module re-exports everything from the [`ostd_test`] crate, as well
199    //! as the test entry point macro.
200    //!
201    //! It is rather discouraged to use the definitions here directly. The
202    //! `ktest` attribute is sufficient for all normal use cases.
203
204    pub use ostd_macros::{test_main as main, test_panic_handler as panic_handler};
205    pub use ostd_test::*;
206}