Re: [PATCH 04/20] rust: alloc: implement `Allocator` for `Kmalloc`
From: Benno Lossin
Date: Sat Jul 06 2024 - 06:37:13 EST
On 04.07.24 19:06, Danilo Krummrich wrote:
> @@ -48,20 +57,54 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: F
> }
> }
>
> +unsafe impl Allocator for Kmalloc {
> + unsafe fn realloc(
> + &self,
> + old_ptr: *mut u8,
> + _old_size: usize,
> + layout: Layout,
> + flags: Flags,
> + ) -> Result<NonNull<[u8]>, AllocError> {
> + let size = aligned_size(layout);
> +
> + // 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 raw_ptr = unsafe {
> + // If `size == 0` and `old_ptr != NULL` `krealloc()` frees the memory behind the
> + // pointer.
> + bindings::krealloc(old_ptr.cast(), size, flags.0).cast()
> + };
> +
> + let ptr = if size == 0 {
> + NonNull::dangling()
> + } else {
> + NonNull::new(raw_ptr).ok_or(AllocError)?
> + };
> +
> + Ok(NonNull::slice_from_raw_parts(ptr, size))
> + }
> +}
> +
> unsafe impl GlobalAlloc for Kmalloc {
Since you remove `alloc` entirely at the end of this series, do we even
need this?
If not, it would be best to just leave the implementation as-is until a
patch removes it entirely.
---
Cheers,
Benno
> unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
> - // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero size by the function safety
> - // requirement.
> - unsafe { krealloc_aligned(ptr::null_mut(), layout, GFP_KERNEL) }
> + let this: &dyn Allocator = self;
> +
> + match this.alloc(layout, GFP_KERNEL) {
> + Ok(ptr) => ptr.as_ptr().cast(),
> + Err(_) => ptr::null_mut(),
> + }
> }