You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.6 KiB

  1. //! Wires rust up to the kheap, so that `alloc::` works.
  2. use spin::Mutex;
  3. use linked_list_allocator::Heap;
  4. use alloc::allocator::{Alloc, Layout, AllocErr};
  5. /// Base location of the kheap.
  6. pub const HEAP_START: usize = 0o_000_001_000_000_0000;
  7. /// Size of the kheap.
  8. pub const HEAP_SIZE: usize = 100 * 1024; // 100 KiB
  9. /// Locked ownership of an optional kheap. Initialized on boot; is `None` before then.
  10. static HEAP: Mutex<Option<Heap>> = Mutex::new(None);
  11. /// Initialize the kheap. Called at boot.
  12. pub unsafe fn heap_init(start: usize, size: usize) {
  13. *HEAP.lock() = Some(Heap::new(start, size));
  14. }
  15. /// Wraps whatever allocator backend we're using, and implements `alloc::allocator::Alloc`.
  16. pub struct Allocator;
  17. unsafe impl<'a> Alloc for &'a Allocator {
  18. #[inline]
  19. unsafe fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
  20. if let Some(ref mut heap) = *HEAP.lock() {
  21. // heap.allocate(layout.size(), layout.align())
  22. // .ok_or(AllocErr::Exhausted { request: layout })
  23. heap.allocate_first_fit(layout)
  24. } else {
  25. panic!("kheap: attempting alloc w/ uninitialized heap");
  26. }
  27. }
  28. #[inline]
  29. unsafe fn dealloc(&mut self, ptr: *mut u8, layout: Layout) {
  30. if let Some(ref mut heap) = *HEAP.lock() {
  31. heap.deallocate(ptr, layout)
  32. // heap.deallocate(ptr, layout.size(), layout.align());
  33. } else {
  34. panic!("kheap: attempting dealloc w/ uninitialized heap");
  35. }
  36. }
  37. #[inline]
  38. fn oom(&mut self, err: AllocErr) -> ! {
  39. panic!("kheap OOM: {:?}", err);
  40. }
  41. }