Skip to content

Commit e6f508e

Browse files
bjorn3herrnst
authored andcommitted
rust: alloc: Add realloc and alloc_zeroed to the GlobalAlloc impl
While there are default impls for these methods, using the respective C api's is faster. Currently neither the existing nor these new GlobalAlloc method implementations are actually called. Instead the __rust_* function defined below the GlobalAlloc impl are used. With rustc 1.71 these functions will be gone and all allocation calls will go through the GlobalAlloc implementation. Link: Rust-for-Linux/linux#68 Signed-off-by: Björn Roy Baron <[email protected]> [boqun: add size adjustment for alignment requirement] Signed-off-by: Boqun Feng <[email protected]> Reviewed-by: Andreas Hindborg <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Miguel Ojeda <[email protected]>
1 parent 2baa576 commit e6f508e

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

rust/kernel/allocator.rs

+27
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,33 @@ unsafe impl GlobalAlloc for KernelAllocator {
5151
bindings::kfree(ptr as *const core::ffi::c_void);
5252
}
5353
}
54+
55+
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
56+
// SAFETY:
57+
// - `new_size`, when rounded up to the nearest multiple of `layout.align()`, will not
58+
// overflow `isize` by the function safety requirement.
59+
// - `layout.align()` is a proper alignment (i.e. not zero and must be a power of two).
60+
let layout = unsafe { Layout::from_size_align_unchecked(new_size, layout.align()) };
61+
62+
// SAFETY:
63+
// - `ptr` is either null or a pointer allocated by this allocator by the function safety
64+
// requirement.
65+
// - the size of `layout` is not zero because `new_size` is not zero by the function safety
66+
// requirement.
67+
unsafe { krealloc_aligned(ptr, layout, bindings::GFP_KERNEL) }
68+
}
69+
70+
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
71+
// SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero size by the function safety
72+
// requirement.
73+
unsafe {
74+
krealloc_aligned(
75+
ptr::null_mut(),
76+
layout,
77+
bindings::GFP_KERNEL | bindings::__GFP_ZERO,
78+
)
79+
}
80+
}
5481
}
5582

5683
#[global_allocator]

0 commit comments

Comments
 (0)