Implement dealloc

This commit is contained in:
2025-09-14 10:20:08 +02:00
parent 44cfcd9f69
commit 4dbbfa1fcf
4 changed files with 83 additions and 36 deletions

2
.vscode/tasks.json vendored
View File

@@ -14,7 +14,7 @@
{ {
"label": "Run QEMU", "label": "Run QEMU",
"type": "shell", "type": "shell",
"command": "llvm-objcopy -O binary target/aarch64-unknown-none/debug/nova target/aarch64-unknown-none/debug/kernel8.img && qemu-system-aarch64 -M raspi3b -cpu cortex-a53 -serial stdio -sd sd.img -display none -kernel ${workspaceFolder}/target/aarch64-unknown-none/debug/kernel8.img -S -s -m 1024", "command": "llvm-objcopy -O binary target/aarch64-unknown-none/debug/nova target/aarch64-unknown-none/debug/kernel8.img && qemu-system-aarch64 -M raspi3b -cpu cortex-a53 -serial stdio -sd sd.img -kernel ${workspaceFolder}/target/aarch64-unknown-none/debug/kernel8.img -S -s -m 1024",
"isBackground": true, "isBackground": true,
"dependsOn": ["Build"] "dependsOn": ["Build"]
} }

View File

@@ -12,13 +12,16 @@ extern "C" {
} }
#[repr(C)] #[repr(C)]
struct Header { pub struct HeapHeader {
next: *mut Header, pub next: *mut HeapHeader,
before: *mut Header, before: *mut HeapHeader,
size: usize, pub size: usize,
free: bool, free: bool,
} }
const HEAP_HEADER_SIZE: usize = size_of::<HeapHeader>();
const MIN_BLOCK_SIZE: usize = 16;
#[derive(Default)] #[derive(Default)]
pub struct Novalloc; pub struct Novalloc;
@@ -28,24 +31,24 @@ unsafe impl GlobalAlloc for Novalloc {
} }
unsafe fn dealloc(&self, ptr: *mut u8, layout: core::alloc::Layout) { unsafe fn dealloc(&self, ptr: *mut u8, layout: core::alloc::Layout) {
todo!() free(ptr).unwrap();
} }
} }
#[global_allocator] #[global_allocator]
static GLOBAL_ALLOCATOR: Novalloc = Novalloc; static GLOBAL_ALLOCATOR: Novalloc = Novalloc;
pub fn init_malloc() { pub fn init_heap() {
unsafe { unsafe {
let heap_end = &raw const __heap_end as usize; let heap_end = &raw const __heap_end as usize;
let heap_start = &raw const __heap_start as usize; let heap_start = &raw const __heap_start as usize;
let s = size_of::<Header>();
ptr::write( ptr::write(
&raw const __heap_start as *mut Header, &raw const __heap_start as *mut HeapHeader,
Header { HeapHeader {
next: null_mut(), next: null_mut(),
before: null_mut(), before: null_mut(),
size: heap_end - heap_start - size_of::<Header>(), size: heap_end - heap_start - HEAP_HEADER_SIZE,
free: true, free: true,
}, },
); );
@@ -53,7 +56,15 @@ pub fn init_malloc() {
} }
pub fn malloc(mut size: usize) -> Result<*mut u8, NovaError> { pub fn malloc(mut size: usize) -> Result<*mut u8, NovaError> {
let mut head = &raw const __heap_start as *mut Header; let mut head = &raw const __heap_start as *mut HeapHeader;
if size == 0 {
return Err(NovaError::EmptyHeapNotAllowed);
}
if size < MIN_BLOCK_SIZE {
size = MIN_BLOCK_SIZE;
}
// Align size to the next 16 bytes // Align size to the next 16 bytes
size += (16 - (size % 16)) % 16; size += (16 - (size % 16)) % 16;
@@ -67,22 +78,28 @@ pub fn malloc(mut size: usize) -> Result<*mut u8, NovaError> {
head = (*head).next; head = (*head).next;
} }
let byte_offset = size_of::<Header>() + size; // Return entire block WITHOUT generating a new header
// if the current block doesn't have enough space to hold: requested size + HEAP_HEADER_SIZE + MIN_BLOCK_SIZE
if (*head).size < size + HEAP_HEADER_SIZE + MIN_BLOCK_SIZE {
(*head).free = false;
return Ok(head.byte_add(HEAP_HEADER_SIZE) as *mut u8);
}
let byte_offset = HEAP_HEADER_SIZE + size;
let new_address = head.byte_add(byte_offset); let new_address = head.byte_add(byte_offset);
// Handle case where free data block is in the center // Handle case where fragmenting center free space
let mut next = null_mut(); let next = (*head).next;
if !(*head).next.is_null() { if !(*head).next.is_null() {
next = (*head).next;
(*next).before = new_address; (*next).before = new_address;
} }
ptr::write( ptr::write(
new_address as *mut Header, new_address as *mut HeapHeader,
Header { HeapHeader {
next, next,
before: head, before: head,
size: (*head).size - size - size_of::<Header>(), size: (*head).size - size - HEAP_HEADER_SIZE,
free: true, free: true,
}, },
); );
@@ -90,20 +107,60 @@ pub fn malloc(mut size: usize) -> Result<*mut u8, NovaError> {
(*head).free = false; (*head).free = false;
(*head).size = size; (*head).size = size;
let data_start_address = new_address.byte_add(size_of::<Header>()); let data_start_address = head.byte_add(HEAP_HEADER_SIZE);
Ok(data_start_address as *mut u8) Ok(data_start_address as *mut u8)
} }
} }
pub fn free(pointer: *mut u8) -> Result<(), NovaError> {
let mut head = unsafe { pointer.sub(HEAP_HEADER_SIZE) as *mut HeapHeader };
unsafe {
// IF prev is free:
// Delete header, add size to previous and fix pointers.
// Move Head left
if !(*head).before.is_null() && (*(*head).before).free {
let before_head = (*head).before;
(*before_head).size += (*head).size + HEAP_HEADER_SIZE;
delete_header(head);
head = before_head;
}
// IF next is free:
// Delete next header and merge size, fix pointers
if !(*head).next.is_null() && (*(*head).next).free {
let next_head = (*head).next;
(*head).size += (*next_head).size + HEAP_HEADER_SIZE;
delete_header(next_head);
}
// Neither: Set free
(*head).free = true;
}
Ok(())
}
unsafe fn delete_header(header: *mut HeapHeader) {
let before = (*header).before;
let next = (*header).next;
if !before.is_null() {
(*before).next = next;
}
if !next.is_null() {
(*next).before = before;
}
}
pub fn traverse_heap_tree() { pub fn traverse_heap_tree() {
let mut pointer_address = &raw const __heap_start as *const Header; let mut pointer_address = &raw const __heap_start as *const HeapHeader;
loop { loop {
let head = unsafe { read_volatile(pointer_address) }; let head = unsafe { read_volatile(pointer_address) };
println!("Header {}", pointer_address as u32); println!("Header {:#x}", pointer_address as u32);
println!("free: {}", head.free); println!("free: {}", head.free);
println!("size: {}", head.size); println!("size: {}", head.size);
println!("hasNext: {}", !head.next.is_null()); println!("hasNext: {}", !head.next.is_null());
println!();
if !head.next.is_null() { if !head.next.is_null() {
pointer_address = head.next; pointer_address = head.next;
} else { } else {

View File

@@ -40,4 +40,5 @@ pub fn mmio_write(address: u32, data: u32) {
pub enum NovaError { pub enum NovaError {
Mailbox, Mailbox,
HeapFull, HeapFull,
EmptyHeapNotAllowed,
} }

View File

@@ -9,11 +9,10 @@ use core::{
}; };
extern crate alloc; extern crate alloc;
use alloc::vec::Vec;
use nova::{ use nova::{
framebuffer::{FrameBuffer, BLUE, GREEN, RED}, framebuffer::{FrameBuffer, BLUE, GREEN, RED},
heap::{init_malloc, malloc, traverse_heap_tree}, heap::init_heap,
irq_interrupt::enable_irq_source, irq_interrupt::enable_irq_source,
mailbox::mb_read_soc_temp, mailbox::mb_read_soc_temp,
peripherals::{ peripherals::{
@@ -89,18 +88,8 @@ unsafe fn zero_bss() {
pub extern "C" fn kernel_main() -> ! { pub extern "C" fn kernel_main() -> ! {
println!("EL: {}", get_current_el()); println!("EL: {}", get_current_el());
// Heap stuff // Initialize the first heap header
init_malloc(); init_heap();
malloc(32).unwrap();
malloc(32).unwrap();
let mut vector = Vec::<u32>::new();
vector.push(5);
malloc(32).unwrap();
vector.push(8);
vector.push(8);
vector.push(8);
sleep_us(500_000); sleep_us(500_000);