Skip to content

Commit

Permalink
mm/alloc: implement Allocator for SvsmAllocator
Browse files Browse the repository at this point in the history
In order to be used along with the new TryBox type, an allocator must
implement the Allocator trait, so implement it for the current global
allocator.

Signed-off-by: Carlos López <[email protected]>
  • Loading branch information
00xc committed Jan 4, 2024
1 parent 576f359 commit 0335561
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/mm/alloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// Author: Joerg Roedel <[email protected]>

use crate::address::{Address, PhysAddr, VirtAddr};
use crate::alloc::{Allocator, TryAllocError};
use crate::error::SvsmError;
#[cfg(any(test, fuzzing))]
use crate::locking::LockGuard;
Expand All @@ -14,7 +15,7 @@ use crate::types::{PAGE_SHIFT, PAGE_SIZE};
use crate::utils::{align_down, align_up, zero_mem_region};
use core::alloc::{GlobalAlloc, Layout};
use core::mem::size_of;
use core::ptr;
use core::ptr::{self, NonNull};
use log;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
Expand Down Expand Up @@ -1287,6 +1288,31 @@ unsafe impl GlobalAlloc for SvsmAllocator {
}
}

unsafe impl Allocator for SvsmAllocator {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, TryAllocError> {
match layout.size() {
0 => Ok(NonNull::slice_from_raw_parts(NonNull::dangling(), 0)),
size => {
// SAFETY: size is nonzero
let raw_ptr = unsafe { self.alloc(layout) };
// FIXME: find a way to return a more correct error here. At
// some point we must reconcile AllocError and
// TryAllocError.
let ptr = NonNull::new(raw_ptr).ok_or(TryAllocError::OutOfMemory)?;
Ok(NonNull::slice_from_raw_parts(ptr, size))
}
}
}

unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
// SAFETY: `layout` is non-zero in size,
// other conditions must be upheld by the caller
if layout.size() != 0 {
self.dealloc(ptr.as_ptr(), layout)
}
}
}

#[cfg_attr(any(target_os = "none"), global_allocator)]
#[cfg_attr(not(target_os = "none"), allow(dead_code))]
static ALLOCATOR: SvsmAllocator = SvsmAllocator::new();
Expand Down

0 comments on commit 0335561

Please sign in to comment.