kernel/mem/
mod.rs

1//! Memory management module.
2//!
3//! This module provides functionality for memory allocation, stack management,
4//! and other memory-related operations needed by the kernel.
5
6pub mod allocator;
7pub mod page;
8pub mod page_cache;
9
10use alloc::{boxed::Box, vec};
11
12use crate::environment::{MAX_NUM_CPUS, STACK_SIZE};
13
14#[repr(C, align(4096))]
15pub struct Stack {
16    pub data: [u32; (STACK_SIZE / 4) * MAX_NUM_CPUS],
17}
18
19impl Stack {
20    pub fn start(&self) -> usize {
21        self.data.as_ptr() as usize
22    }
23
24    pub fn end(&self) -> usize {
25        self.start() + self.size()
26    }
27
28    pub fn size(&self) -> usize {
29        STACK_SIZE * MAX_NUM_CPUS
30    }
31}
32
33#[unsafe(no_mangle)]
34pub static mut KERNEL_STACK: Stack = Stack {
35    data: [0xdeadbeef; STACK_SIZE / 4 * MAX_NUM_CPUS],
36};
37
38/// Allocates a block of memory of the specified size from the kernel heap.
39///
40/// # Arguments
41///
42/// * `size` - The size of the memory block to allocate.
43///
44/// # Returns
45///
46/// * A pointer to the allocated memory block.
47///
48pub fn kmalloc(size: usize) -> *mut u8 {
49    Box::into_raw(vec![0u8; size].into_boxed_slice()) as *mut u8
50}
51
52/// Frees a block of memory previously allocated with `kmalloc`.
53///
54/// # Arguments
55///
56/// * `ptr` - A pointer to the memory block to free.
57/// * `size` - The size of the memory block to free.
58///
59pub fn kfree(ptr: *mut u8, size: usize) {
60    unsafe {
61        let _ = Box::<[u8]>::from_raw(core::slice::from_raw_parts_mut(ptr, size));
62    }
63}
64
65pub fn init_bss() {
66    unsafe extern "C" {
67        static mut __BSS_START: u8;
68        static mut __BSS_END: u8;
69    }
70
71    unsafe {
72        let bss_start = &raw mut __BSS_START as *mut u8;
73        let bss_end = &raw mut __BSS_END as *mut u8;
74        let bss_size = bss_end as usize - bss_start as usize;
75        core::ptr::write_bytes(bss_start, 0, bss_size);
76    }
77}
78
79unsafe extern "C" {
80    pub static __KERNEL_SPACE_START: usize;
81    pub static __KERNEL_SPACE_END: usize;
82    pub static __FDT_RESERVED_START: usize;
83    pub static __FDT_RESERVED_END: usize;
84}