[PATCH 08/20] rust: alloc: implement `KVmalloc` allocator

From: Danilo Krummrich
Date: Thu Jul 04 2024 - 13:11:03 EST


Implement `Allocator` for `KVmalloc`, an `Allocator` that tries to
allocate memory wth `kmalloc` first and, on failure, falls back to
`vmalloc`.

All memory allocations made with `KVmalloc` end up in
`kvrealloc_noprof()`; all frees in `kvfree()`.

Signed-off-by: Danilo Krummrich <dakr@xxxxxxxxxx>
---
rust/kernel/alloc/allocator.rs | 35 +++++++++++++++++++++++++++++
rust/kernel/alloc/allocator_test.rs | 1 +
2 files changed, 36 insertions(+)

diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs
index 0a4f27c5c3a6..d561c594cc7f 100644
--- a/rust/kernel/alloc/allocator.rs
+++ b/rust/kernel/alloc/allocator.rs
@@ -22,6 +22,12 @@
/// contiguous kernel virtual space.
pub struct Vmalloc;

+/// The kvmalloc kernel allocator.
+///
+/// Attempt to allocate physically contiguous memory, but upon failure, fall back to non-contiguous
+/// (vmalloc) allocation.
+pub struct KVmalloc;
+
/// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment.
fn aligned_size(new_layout: Layout) -> usize {
// Customized layouts from `Layout::from_size_align()` can have size < align, so pad first.
@@ -167,6 +173,35 @@ unsafe fn realloc(
}
}

+unsafe impl Allocator for KVmalloc {
+ unsafe fn realloc(
+ &self,
+ old_ptr: *mut u8,
+ old_size: usize,
+ layout: Layout,
+ flags: Flags,
+ ) -> Result<NonNull<[u8]>, AllocError> {
+ let size = aligned_size(layout);
+
+ let ptr = if size == 0 {
+ // SAFETY: `old_ptr` is guaranteed to be previously allocated with this `Allocator` or
+ // NULL.
+ unsafe { bindings::kvfree(old_ptr.cast()) };
+ NonNull::dangling()
+ } else {
+ // SAFETY: `old_ptr` is guaranteed to point to valid memory with a size of at least
+ // `old_size`, which was previously allocated with this `Allocator` or NULL.
+ let raw_ptr = unsafe {
+ bindings::kvrealloc_noprof(old_ptr.cast(), old_size, size, flags.0).cast()
+ };
+
+ NonNull::new(raw_ptr).ok_or(AllocError)?
+ };
+
+ Ok(NonNull::slice_from_raw_parts(ptr, size))
+ }
+}
+
#[global_allocator]
static ALLOCATOR: Kmalloc = Kmalloc;

diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/allocator_test.rs
index b2d7db492ba6..f0e96016b196 100644
--- a/rust/kernel/alloc/allocator_test.rs
+++ b/rust/kernel/alloc/allocator_test.rs
@@ -8,6 +8,7 @@

pub struct Kmalloc;
pub type Vmalloc = Kmalloc;
+pub type KVmalloc = Kmalloc;

unsafe impl Allocator for Kmalloc {
unsafe fn realloc(
--
2.45.2