pub mod address_space;
pub mod paging;
pub use address_space::{create_kernel_address_space, AddressSpace, MemoryArea, MemoryAreaType};
pub use ahrightos_memory::*;
pub use paging::{
map_page, map_page_verbose, translate_addr as translate_addr_current, unmap_page,
walk_page_table, walk_page_table_verbose,
};
pub fn init(kernel_end: usize) -> MemoryManager {
const MEMORY_START: usize = 0x8000_0000;
const MEMORY_SIZE: usize = 128 * 1024 * 1024;
let memory_end = MEMORY_START + MEMORY_SIZE;
crate::serial_println!("[MEMORY] Initializing memory management");
crate::serial_println!("[MEMORY] Kernel end: {:#x}", kernel_end);
crate::serial_println!(
"[MEMORY] Memory range: {:#x} - {:#x}",
MEMORY_START,
memory_end
);
crate::serial_println!(
"[MEMORY] Frame allocator initialized: {:#x} - {:#x}",
(kernel_end + PAGE_SIZE - 1) & !(PAGE_SIZE - 1),
memory_end
);
MemoryManager::new(kernel_end, memory_end)
}
pub fn create_example_mapping(
page: Page,
frame_allocator: &mut SimpleFrameAllocator,
) -> Result<(), &'static str> {
let frame = frame_allocator
.allocate()
.ok_or("Failed to allocate frame")?;
crate::serial_println!(
"[MEMORY] Example mapping: {:?} -> {:?}",
page.start_address(),
frame.start_address()
);
Ok(())
}
pub fn translate_addr(vaddr: VirtAddr) -> Option<PhysAddr> {
use riscv::register::satp;
let satp_value = satp::read();
let ppn = satp_value.ppn();
let root_paddr = PhysAddr::new(ppn << 12);
walk_page_table(root_paddr, vaddr)
}
#[cfg(test)]
mod tests {
use super::*;
#[test_case]
fn test_virt_addr_vpn() {
let addr = VirtAddr::new(0x1234_5678);
assert_eq!(addr.page_offset(), 0x678);
}
#[test_case]
fn test_frame_alloc_dealloc_reuse() {
let mut allocator = SimpleFrameAllocator::new(0x8020_0000, 0x8030_0000);
let f1 = allocator.allocate().expect("first alloc");
let f2 = allocator.allocate().expect("second alloc");
assert_ne!(f1.start_address().as_usize(), f2.start_address().as_usize());
let f1_addr = f1.start_address().as_usize();
allocator.deallocate(f1);
let f3 = allocator.allocate().expect("reuse freed frame");
assert_eq!(f3.start_address().as_usize(), f1_addr);
}
#[test_case]
fn test_frame_alloc_exhaustion() {
let mut allocator = SimpleFrameAllocator::new(0x8020_0000, 0x8020_1000);
assert!(allocator.allocate().is_some());
assert!(allocator.allocate().is_none());
}
}