ahrightos-kernel 0.1.0

RISC-V 64 Rust teaching kernel for AhRightOS.
Documentation
//! Interrupt-safe wrapper around `linked_list_allocator::Heap`.
//!
//! The allocator is used after timer interrupts and preemptive scheduling are
//! enabled. Holding the heap lock across a timer interrupt can deadlock when the
//! scheduler resumes another task that also allocates, so global alloc/dealloc
//! run with interrupts disabled.

use super::Locked;
use alloc::alloc::{GlobalAlloc, Layout};
use core::{ptr, ptr::NonNull};
use linked_list_allocator::Heap;

pub struct LinkedListAllocator {
    heap: Heap,
    heap_start: usize,
    heap_end: usize,
}

impl LinkedListAllocator {
    pub const fn new() -> Self {
        Self {
            heap: Heap::empty(),
            heap_start: 0,
            heap_end: 0,
        }
    }

    /// # Safety
    ///
    /// The caller must provide an unused, valid heap region for the lifetime of
    /// the kernel.
    pub unsafe fn init(&mut self, heap_start: usize, heap_size: usize) {
        self.heap_start = heap_start;
        self.heap_end = heap_start + heap_size;
        unsafe {
            self.heap.init(heap_start as *mut u8, heap_size);
        }
    }

    fn contains_allocation(&self, ptr: *mut u8, layout: Layout) -> bool {
        if ptr.is_null() || layout.size() == 0 {
            return false;
        }

        let addr = ptr as usize;
        let Some(end) = addr.checked_add(layout.size()) else {
            return false;
        };

        addr >= self.heap_start && end <= self.heap_end
    }
}

impl Default for LinkedListAllocator {
    fn default() -> Self {
        Self::new()
    }
}

unsafe impl GlobalAlloc for Locked<LinkedListAllocator> {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        crate::interrupts::without_interrupts(|| {
            let mut allocator = self.lock();
            match allocator.heap.allocate_first_fit(layout) {
                Ok(ptr) => ptr.as_ptr(),
                Err(_) => ptr::null_mut(),
            }
        })
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        crate::interrupts::without_interrupts(|| {
            let mut allocator = self.lock();
            if !allocator.contains_allocation(ptr, layout) {
                return;
            }

            let Some(ptr) = NonNull::new(ptr) else {
                return;
            };
            unsafe {
                allocator.heap.deallocate(ptr, layout);
            }
        });
    }
}