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