Re: [PATCH v6 06/26] rust: alloc: implement `Vmalloc` allocator

From: Benno Lossin
Date: Sat Aug 31 2024 - 01:21:51 EST


On 16.08.24 02:10, Danilo Krummrich wrote:
> @@ -63,6 +73,9 @@ impl ReallocFunc {
> // INVARIANT: `krealloc` satisfies the type invariants.
> const KREALLOC: Self = Self(bindings::krealloc);
>
> + // INVARIANT: `vrealloc` satisfies the type invariants.
> + const VREALLOC: Self = Self(bindings::vrealloc);
> +
> /// # Safety
> ///
> /// This method has the same safety requirements as [`Allocator::realloc`].
> @@ -141,6 +154,25 @@ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
> }
> }
>
> +unsafe impl Allocator for Vmalloc {

The same safety comment as with `Kmalloc` should fit here (and with
`KVmalloc` too).

---
Cheers,
Benno

> + #[inline]
> + unsafe fn realloc(
> + ptr: Option<NonNull<u8>>,
> + layout: Layout,
> + flags: Flags,
> + ) -> Result<NonNull<[u8]>, AllocError> {
> + // TODO: Support alignments larger than PAGE_SIZE.
> + if layout.align() > bindings::PAGE_SIZE {
> + pr_warn!("Vmalloc does not support alignments larger than PAGE_SIZE yet.\n");
> + return Err(AllocError);
> + }
> +
> + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously
> + // allocated with this `Allocator`.
> + unsafe { ReallocFunc::VREALLOC.call(ptr, layout, flags) }
> + }
> +}
> +
> #[global_allocator]
> static ALLOCATOR: Kmalloc = Kmalloc;
>
> diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/allocator_test.rs
> index 4785efc474a7..e7bf2982f68f 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.46.0
>