Re: [PATCH 07/20] rust: alloc: implement `Vmalloc` allocator

From: Benno Lossin
Date: Sat Jul 06 2024 - 06:41:50 EST


On 04.07.24 19:06, Danilo Krummrich wrote:
> @@ -112,6 +118,55 @@ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
> }
> }
>
> +unsafe impl Allocator for Vmalloc {
> + unsafe fn realloc(
> + &self,
> + src: *mut u8,
> + old_size: usize,
> + layout: Layout,
> + flags: Flags,
> + ) -> Result<NonNull<[u8]>, AllocError> {
> + let mut size = aligned_size(layout);
> +
> + let dst = if size == 0 {
> + // SAFETY: `src` is guaranteed to be previously allocated with this `Allocator` or NULL.
> + unsafe { bindings::vfree(src.cast()) };
> + NonNull::dangling()
> + } else if size <= old_size {
> + size = old_size;
> + NonNull::new(src).ok_or(AllocError)?
> + } else {
> + // SAFETY: `src` 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 dst = unsafe { bindings::__vmalloc_noprof(size as u64, flags.0) };
> +
> + // Validate that we actually allocated the requested memory.
> + let dst = NonNull::new(dst.cast()).ok_or(AllocError)?;
> +
> + if !src.is_null() {
> + // SAFETY: `src` is guaranteed to point to valid memory with a size of at least
> + // `old_size`; `dst` is guaranteed to point to valid memory with a size of at least
> + // `size`.
> + unsafe {
> + core::ptr::copy_nonoverlapping(
> + src,
> + dst.as_ptr(),
> + core::cmp::min(old_size, size),
> + )
> + };
> +
> + // SAFETY: `src` is guaranteed to be previously allocated with this `Allocator` or
> + // NULL.
> + unsafe { bindings::vfree(src.cast()) }
> + }
> +
> + dst
> + };

If we had not a single realloc, but shrink/grow/free/alloc, then we
would not need these checks here, I personally would prefer that, what
do you guys think?

---
Cheers,
Benno

> +
> + Ok(NonNull::slice_from_raw_parts(dst, size))
> + }
> +}
> +
> #[global_allocator]
> static ALLOCATOR: Kmalloc = Kmalloc;
>
> diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/allocator_test.rs
> index 3a0abe65491d..b2d7db492ba6 100644
> --- a/rust/kernel/alloc/allocator_test.rs
> +++ b/rust/kernel/alloc/allocator_test.rs
> @@ -7,6 +7,7 @@
> use core::ptr::NonNull;
>
> pub struct Kmalloc;
> +pub type Vmalloc = Kmalloc;
>
> unsafe impl Allocator for Kmalloc {
> unsafe fn realloc(
> --
> 2.45.2
>