From f9590a92dbb8e87ee3c480c57ab93d6fb8478bd4 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 4 Dec 2026 08:07:47 -0500 Subject: [PATCH] rust: alloc: short-circuit zero-size realloc of null pointers Every empty KVec::drop() calls A::free(ptr, old_layout) unconditionally. ReallocFunc::call() turns old_layout.size() == 0 into a NULL pointer and still invokes C FFI krealloc_node_align/vrealloc_node_align/kvrealloc_node_align with (NULL, 0), which immediately calls kfree(NULL)/vfree(NULL) and returns a value that ReallocFunc::call() discards before returning dangling_from_layout(layout). Zero-size allocations from None take the same unnecessary FFI trip. Return dangling_from_layout(layout) directly when size == 0 and the normalized pointer is NULL, avoiding the FFI call and kfree(NULL) on every empty KVec drop and zero-size allocation. Signed-off-by: Satya Benson --- rust/kernel/alloc/allocator.rs | 38 ++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index 349a4f665fc4e..9107ac8e9aeff 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -114,6 +114,13 @@ impl ReallocFunc { None => ptr::null(), }; + if size == 0 && ptr.is_null() { + return Ok(NonNull::slice_from_raw_parts( + crate::alloc::dangling_from_layout(layout), + 0, + )); + } + // SAFETY: // - `self.0` is one of `krealloc`, `vrealloc`, `kvrealloc` and thus only requires that // `ptr` is NULL or valid. @@ -322,4 +329,35 @@ mod tests { Ok(()) } + + #[test] + fn test_zero_size() -> Result { + for align in [1, 8, 64, 4096] { + let layout = Layout::from_size_align(0, align).map_err(|_| EINVAL)?; + // SAFETY: Zero-size alloc and free are always valid for all kernel allocators. + unsafe { + let km = Kmalloc::realloc(None, layout, Layout::new::<()>(), GFP_KERNEL, NumaNode::NO_NODE)?; + assert_eq!(km.len(), 0); + assert_eq!(km.cast::().as_ptr() as usize & (align - 1), 0); + Kmalloc::free(km.cast(), layout); + + let vm = Vmalloc::realloc(None, layout, Layout::new::<()>(), GFP_KERNEL, NumaNode::NO_NODE)?; + assert_eq!(vm.len(), 0); + assert_eq!(vm.cast::().as_ptr() as usize & (align - 1), 0); + Vmalloc::free(vm.cast(), layout); + + let kvm = KVmalloc::realloc(None, layout, Layout::new::<()>(), GFP_KERNEL, NumaNode::NO_NODE)?; + assert_eq!(kvm.len(), 0); + assert_eq!(kvm.cast::().as_ptr() as usize & (align - 1), 0); + KVmalloc::free(kvm.cast(), layout); + } + } + + let empty: KVec = KVec::new(); + drop(empty); + let empty_cap: KVec = KVec::with_capacity(0, GFP_KERNEL)?; + drop(empty_cap); + + Ok(()) + } }