-
Notifications
You must be signed in to change notification settings - Fork 46
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
mm/alloc: implement Allocator for SvsmAllocator
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
Showing
1 changed file
with
27 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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; | ||
|
@@ -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)] | ||
|
@@ -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(); | ||
|