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

Danilo Krummrich posted 20 patches 1 year, 7 months ago
There is a newer version of this series
[PATCH 07/20] rust: alloc: implement `Vmalloc` allocator
Posted by Danilo Krummrich 1 year, 7 months ago
Implement `Allocator` for `Vmalloc`, the kernel's virtually contiguous
allocator, typically used for larger objects, (much) larger than page
size.

All memory allocations made with `Vmalloc` end up in
`__vmalloc_noprof()`; all frees in `vfree()`.

Signed-off-by: Danilo Krummrich <dakr@redhat.com>
---
 rust/bindings/bindings_helper.h     |  1 +
 rust/kernel/alloc/allocator.rs      | 55 +++++++++++++++++++++++++++++
 rust/kernel/alloc/allocator_test.rs |  1 +
 3 files changed, 57 insertions(+)

diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
index ddb5644d4fd9..f10518045c16 100644
--- a/rust/bindings/bindings_helper.h
+++ b/rust/bindings/bindings_helper.h
@@ -15,6 +15,7 @@
 #include <linux/refcount.h>
 #include <linux/sched.h>
 #include <linux/slab.h>
+#include <linux/vmalloc.h>
 #include <linux/wait.h>
 #include <linux/workqueue.h>
 
diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs
index 1860cb79b875..0a4f27c5c3a6 100644
--- a/rust/kernel/alloc/allocator.rs
+++ b/rust/kernel/alloc/allocator.rs
@@ -16,6 +16,12 @@
 /// `bindings::krealloc`.
 pub struct Kmalloc;
 
+/// The virtually contiguous kernel allocator.
+///
+/// The vmalloc allocator allocates pages from the page level allocator and maps them into the
+/// contiguous kernel virtual space.
+pub struct Vmalloc;
+
 /// 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.
@@ -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
+        };
+
+        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
Re: [PATCH 07/20] rust: alloc: implement `Vmalloc` allocator
Posted by Benno Lossin 1 year, 7 months ago
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
> 
Re: [PATCH 07/20] rust: alloc: implement `Vmalloc` allocator
Posted by Danilo Krummrich 1 year, 7 months ago
On Sat, Jul 06, 2024 at 10:41:28AM +0000, Benno Lossin wrote:
> 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? 

Yeah, but look at `Kmalloc`, you'd have these checks in `Kmalloc`'s shrink/grow
functions instead, since `krealloc()` already behaves this way.

Personally, I don't see much value in `shrink` and `grow`. I think
implementations end up calling into some `realloc` with either `new < old` or
`new > old` anyway.

> 
> ---
> 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
> > 
>
Re: [PATCH 07/20] rust: alloc: implement `Vmalloc` allocator
Posted by Benno Lossin 1 year, 7 months ago
On 06.07.24 13:13, Danilo Krummrich wrote:
> On Sat, Jul 06, 2024 at 10:41:28AM +0000, Benno Lossin wrote:
>> 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?
> 
> Yeah, but look at `Kmalloc`, you'd have these checks in `Kmalloc`'s shrink/grow
> functions instead, since `krealloc()` already behaves this way.

In the kmalloc case you would have different instantiations, no checks.
IIUC for freeing you would do `krealloc(ptr, 0, flags)`.

> Personally, I don't see much value in `shrink` and `grow`. I think
> implementations end up calling into some `realloc` with either `new < old` or
> `new > old` anyway.

I think a `resize` would make more sense. In general, splitting
resizing, creating and freeing makes sense to me.

---
Cheers,
Benno
Re: [PATCH 07/20] rust: alloc: implement `Vmalloc` allocator
Posted by Danilo Krummrich 1 year, 7 months ago
On Sat, Jul 06, 2024 at 01:21:39PM +0000, Benno Lossin wrote:
> On 06.07.24 13:13, Danilo Krummrich wrote:
> > On Sat, Jul 06, 2024 at 10:41:28AM +0000, Benno Lossin wrote:
> >> 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?
> > 
> > Yeah, but look at `Kmalloc`, you'd have these checks in `Kmalloc`'s shrink/grow
> > functions instead, since `krealloc()` already behaves this way.
> 
> In the kmalloc case you would have different instantiations, no checks.
> IIUC for freeing you would do `krealloc(ptr, 0, flags)`.

We can't allow to shrink on a `grow` call and we can't allow to grow on a
`shrink` call, so we have to do the checks there before we call into krealloc().

Unless, we say that passing stupid arguments to `grow` can actually shrink and
vice versa, but then we can just keep `realloc`, right?

> 
> > Personally, I don't see much value in `shrink` and `grow`. I think
> > implementations end up calling into some `realloc` with either `new < old` or
> > `new > old` anyway.
> 
> I think a `resize` would make more sense. In general, splitting
> resizing, creating and freeing makes sense to me.

Please see the other mail thread.

> 
> ---
> Cheers,
> Benno
>